如何在django模型中找到3个最高值或最大值



我在django模型中有一个类,如何在其中找到3个最大值?我需要for for for循环吗?或者我需要上课吗?

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}"

我有最高价的代码,但我也需要3个最高价。

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

我在django模型中有一个类,如何在其中找到3个最大值?

使用降序_by(注意"-Price"中的-(和切片的组合

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

您可以按价格订购查询集,然后获得前3个查询集。它会给你所需要的。这是文档的链接

所以你可以做:

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

其中,order_by使用给定字段值对查询集进行排序,[:3]将其限制为3项。

最新更新