Home > Enterprise >  'NoneType' object has no attribute 'add' in Django Models
'NoneType' object has no attribute 'add' in Django Models

Time:08-05

I have the next:'NoneType' object has no attribute 'add'. When I try to add a value to a null field (null=True) with auction.winner.add(u) it gives me that exception. I am working with Django Models and it looks like is not allowed to add a value to a null Field almost with this method. Is there some way to do this?

My models.py:

class Bids(models.Model):
    bid = models.IntegerField(max_length=64)
    user_id2 = models.ForeignKey(User, on_delete = models.CASCADE, related_name="user_id2")

class Comments(models.Model):
    comments = models.TextField(max_length=64)
    user_id3 = models.ForeignKey(User, on_delete = models.CASCADE, related_name="user_id3")
    
class Categories(models.Model):
    categories = models.CharField(max_length=64)
    
class Auction(models.Model):
    title = models.CharField(max_length=64)
    description = models.CharField(max_length=64)
    starting_bid = models.IntegerField(max_length=64)
    photo_url = models.CharField(max_length=64, blank=True, null=True)
    category = models.ForeignKey(Categories, on_delete = models.CASCADE, related_name="category")
    user_id = models.ForeignKey(User, on_delete = models.CASCADE, related_name="user_id")
    winner = models.ForeignKey(User, blank=True, null=True, on_delete = models.CASCADE, related_name="winner")
    bids = models.ManyToManyField(Bids, blank=True, related_name="bi")
    comments = models.ManyToManyField(Comments, blank=True, related_name="co")

Then my function:

def win(request, auction_id):
    if request.method == "POST":
        auction = Auction.objects.get(pk=int(auction_id))
        auction_bids = auction.bids.all()
        j = 0
        for i in auction_bids:
            if i.bid > j:
                j = i.bid
                k = i.user_id2.id
            else:
                pass
        u = User.objects.get(pk=int(k))
        auction.winner.update(u)

CodePudding user response:

Change winner_id and then save auction.


def win(request, auction_id):
    if request.method == "POST":
        auction = Auction.objects.get(pk=int(auction_id))
        auction_bids = auction.bids.all()
        j = 0
        for i in auction_bids:
            if i.bid > j:
                j = i.bid
                k = i.user_id2.id
            else:
                pass
        auction.winner_id = k
        auction.save(update_fields=["winner"])

CodePudding user response:

Check if it’s null and then initialise it to the id of the winner user.

  • Related