繁体   English   中英

如何在 django model 中找到 3 个最高值或最大值?

[英]How can I find 3 top or max value in django model?

我在 django model 中有一个 class,我怎样才能在其中找到 3 个最大值? 我需要for循环吗? 或者我需要任何 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}"

我有最高价格的代码,但我也需要 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 model 中有一个 class,我怎样才能在其中找到 3 个最大值?

结合降序 order_by (注意-"-Price"中)和切片

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

您可以按价格对查询集进行排序,然后获取其中的前 3 个。 它会给你你需要的东西。这是文档的链接

所以你可以这样做:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM