使用django中的聚合获取最小值字段名

时间:2022-09-17 22:51:13

I have a model with some fields like below

我有一个模型,其中有些字段如下所示

class Choclate(models.Model):
    name = models.CharField(max_length=256)
    price = models.IntegerField()

So i want to get the field name that has the lowest price value, so in order to get the lowest price value, we can do like below using Aggregations

我想要得到价格最低的字段名,为了得到价格最低的字段名,我们可以使用聚合

from django.db.models import Avg, Max, Min

choclates = Choclate.objects.all()
lowest_price = choclates.aggregate(Min('price'))

So finally how to get the field name, that related to lowest price value in django ?

最后,如何获得与django中最低价相关的字段名?

2 个解决方案

#1


9  

You can try below code to get exact thing you want

您可以尝试下面的代码来得到您想要的东西

>>> from django.db.models import Min
>>> Choclate.objects.filter().values_list('name').annotate(Min('price')).order_by('price')[0]
(u'First1', 10)
>>>

First1 is the field name having price = 10 which is lowest value.

First1是具有price = 10的字段名,这是最低的值。

#2


1  

If you pass the Min as positional argument, then the field's name is price__min. Otherwise, if you pass it as keyword argument, i.e. aggregate(my_min=Min('price')), then it will be available with the same name as the argument, in this case my_min. Docs

如果将Min作为位置参数传递,那么字段的名称为price__min。否则,如果将其作为关键字参数传递,即聚合(my_min=Min('price')),那么它将具有与参数相同的名称,在本例中为my_min。文档

#1


9  

You can try below code to get exact thing you want

您可以尝试下面的代码来得到您想要的东西

>>> from django.db.models import Min
>>> Choclate.objects.filter().values_list('name').annotate(Min('price')).order_by('price')[0]
(u'First1', 10)
>>>

First1 is the field name having price = 10 which is lowest value.

First1是具有price = 10的字段名,这是最低的值。

#2


1  

If you pass the Min as positional argument, then the field's name is price__min. Otherwise, if you pass it as keyword argument, i.e. aggregate(my_min=Min('price')), then it will be available with the same name as the argument, in this case my_min. Docs

如果将Min作为位置参数传递,那么字段的名称为price__min。否则,如果将其作为关键字参数传递,即聚合(my_min=Min('price')),那么它将具有与参数相同的名称,在本例中为my_min。文档