'How to make a model field equal to a queryset result

I am new to django and coding in general. I have this project that I am trying to code thats basically an auctions website.

I am facing some difficulties structuring the models though.

Here are 2 models of all models

class Listing(models.Model):
    title = models.CharField(max_length=64)
    image = models.URLField(null=True, blank=True)
    description = models.CharField(max_length=64)
    starting_price = models.DecimalField(max_digits=7, decimal_places=2)    

    current_price = #highest bid price
    bids_count = #count of bids

    lister = models.ForeignKey(User, on_delete=models.CASCADE, related_name="listings")

    def __str__(self):
        return f"Title: {self.title} ({self.id}), Lister: {self.lister.username}"


class Bid(models.Model):
    listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="bids")
    bidder = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="bids")
    amount = models.DecimalField(max_digits=7, decimal_places=2)
    time = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"Bid by {self.bidder.username} on {self.listing.title} ({self.listing.id}) for an amount of {self.amount}"

I am trying to let the current price equal to the highest bid of that listing

current_price = Listing.bid.objects.all().aggregate(Max("amount"))

And count the number of bids

bids_count = Listing.bid.count()

I know we cant place querysets inside models fields like I have done but i did it to demonstrate my issue.

Surely there is some way around this but I just cant figure it out.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source