Home > Net >  How can I find 3 top or max value in django model?
How can I find 3 top or max value in django model?

Time:10-06

I have a class in django model and how can I find 3 maximum value in it? Do I need for into for loop? or Do I need any class?

class Prices (models.Model):

user = models.ForeignKey(User,on_delete=models.CASCADE)
Price = models.IntegerField()
page = models.ManyToManyField(Listing_page,blank=True,related_name='Price')
def __str__(self) -> str:
    return f"{self.id} : {self.Price}"

I have follow code for top price but I need 3 top price too.

big_price = None

for num in post.Price.all():
    if (big_price is None or num.Price > big_price.Price):
        big_price = num

CodePudding user response:

I have a class in django model and how can I find 3 maximum value in it?

With a combination of descending order_by (notice - in "-Price") and slicing

post.Price.all().order_by("-Price")[:3]

CodePudding user response:

You can order the queryset by price and then get the first 3 of them. It will give you what you need.Here is the link to the documentation

So you can do:

Prices.objects.order_by("-Price")[:3]

Where order_by orders the queryset with the given fields value, [:3] limits it to 3 items.

  • Related