Django models, get Max value from other table using related_name

Viewed 175

I have this django model:

class User(AbstractUser):
    ...

class Auction(models.Model):
    title = models.CharField(max_length=64)
    description = models.CharField(max_length=1024)
    ...

class Bid(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE, related_name="bids")
    auction = models.ForeignKey(Auction, on_delete=models.CASCADE, related_name="bids")
    price = models.IntegerField(default=0)
    ...

I want to list some Auction objects showing max Bid (or last Bid). Note that in the models I used 'bids' as related_name to access Bids from an Auction object. Trying to employ related_name feature, i did this:

def index(request):
    return render(request, "auctions/index.html", {
                 "listings": Auction.objects.all().annotate(price=Max('bids'))
            })

Apparently, price=Max('bids') returns the max value of id column in bids. But I need max value of price field.

I know I can achieve this using raw queries, or looping through results of Auction.objects.all(), but I wonder if there is a way for this in Django's db abstraction methods.

1 Answers

You specify this with two consecutive underscores (__) and the field name

def index(request):
    return render(request, "auctions/index.html", {
        'listings': Auction.objects.annotate(price=Max('bids__price'))
    })
Related