Home > Net >  Django - Get user with highest bid
Django - Get user with highest bid

Time:10-22

I need to get the user who placed the highest bid for the listing on an auction site.

models.py:

class Listing(models.Model):

class Category(models.TextChoices):
    BOOKS = 'Books'
    SPORTS = 'Sports'
    DEATHLY_HALLOWS = 'Deathly Hallows'
    CLOTHING = 'Clothing'
    WANDS = 'Wands'
    JEWELRY = 'Jewelry'

title = models.CharField(max_length=64)
description = models.TextField(max_length=320)
starting_bid = models.DecimalField(max_digits=10, decimal_places=2, default=0)
current_price = models.DecimalField(max_digits=10, decimal_places=2, default=0 )
img_url = models.URLField(blank=True)
category = models.CharField(choices=Category.choices, max_length=64, blank=True)
is_closed = models.BooleanField(default=False)
user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)  
winner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="Winner") 

def __str__(self):
    return f"{self.title}"

class Bid(models.Model):
    listing = models.ForeignKey(Listing, on_delete=models.CASCADE, default=1)
    bid = models.DecimalField(max_digits=10, decimal_places=2)
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="Bidder")  

views.py:

def listing(request, listing_id):

highest_bid = Bid.objects.aggregate(Max('bid'))
winner = highest_bid.user

print(winner)

Returns the error: 'dict' object has no attribute 'user'.

How can I get the user from the maximum bid placed on the listing?

CodePudding user response:

Order the Bids by the bid:

def listing(request, listing_id):
    highest_bid = Bid.objects.latest('bid')
    winner = highest_bid.user
    print(winner)
    # …
  • Related