如何为一个字段中的最高值按另一个字段中的每个值分组的查询集过滤?

时间:2020-03-10 14:20:48

标签: django aggregate django-queryset

如果我有这样的模型

from django.db import models

class Thing(models.Model):
    name = models.CharField(max_length=255, unique = True, null=False)
    version = models.IntegerField(null = False)
    type = models.CharField(max_length=255, null=False)

我有一堆类似

的条目
Thing.objects.create(name = "foo1", version = 1, type = "A")
Thing.objects.create(name = "foo2", version = 2, type = "A")
Thing.objects.create(name = "bar1", version = 1, type = "B")
Thing.objects.create(name = "bar2", version = 2, type = "B")
Thing.objects.create(name = "bar3", version = 3, type = "B")

如何编写单个Django查询,该查询将为type类型最高的version中的每个类型给我一个条目?因此,此结果:

Queryset< Thing(name = "foo2", version = 2, type = "A"), 
Thing(name = "bar3", version = 3, type = "B") >

我正在看这里的文档; https://docs.djangoproject.com/en/3.0/topics/db/aggregation/

很容易做到这样;

Thing.objects.aggregate(Max('version'))

但这只会给我Thing(name = "bar3", version = 3, type = "B")

1 个答案:

答案 0 :(得分:0)

这按high分组,并按最大 const higherTest = test.filter(item => item.id === 'high'); const lowerTest = test.filter(item => item.id === 'low'); 过滤:

type