django queryset - 按值分类和过滤

时间:2017-05-12 19:51:35

标签: python django python-3.x django-models django-queryset

我有两个属性的模型:

class Fruit(models.Model)
   name = models.CharField(max_length=30)
   days_left_to_consumption = models.IntegerField()

给我数据库对象:

{"name":"apple", "days_left_to_consumption": 2},
{"name":"apple", "days_left_to_consumption": 3},
{"name":"pineaple", "days_left_to_consumption": 2},
{"name":"pineaple", "days_left_to_consumption": 1}

我想创建queryset以按“name”属性对结果进行分类(每个不同的水果名称只出现一次),但是为每个具有较高值“days_left_to_consumption”的diffrient水果对象获取。我想从上面的例子得到的结果是:

{"name":"apple", "days_left_to_consumption": 3},
{"name":"pineaple", "days_left_to_consumption": 2}

你有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您需要按名称对项目进行分组,并获得最大的days_left_to_consumption:

from django.db.models import Max
fruits = Fruit.objects.values('name').annotate(max_days_left_to_consumption=Max('days_left_to_consumption'))