Django ORM查询GROUP BY多列组合MAX [英] Django ORM query GROUP BY multiple columns combined by MAX
问题描述
类MM(models.Model):
a = models.IntegerField )
b = models.IntegerField()
c = models.DateTimeField(auto_now_add = True)
我有多行, a
等于 b
,我想执行以下SQL查询:
SELECT a,b,MAX(c)AS max FROM MM GROUP BY b,a;
如何使用Django ORM?我尝试过使用注释的不同方法,但现在运气到目前为止。
非常感谢!
我想你可以这样做:
MM.objects.all() 'b','a')。注释(max = Max('c'))
注意你需要导入一些东西来使用Max: from django.db.models import Max
值('b','a')
将给出 GROUP BY b,a
和 annotate 。)
将计算查询中的MAX。
I am using Django with MySQL. I have a model similar to the following:
class MM(models.Model):
a = models.IntegerField()
b = models.IntegerField()
c = models.DateTimeField(auto_now_add=True)
I have multiple rows that a
is equal to b
, and I want to perform the following SQL query:
SELECT a, b, MAX(c) AS max FROM MM GROUP BY b, a;
How can this be done with Django ORM? I have tried different approaches using annotations, but now luck so far.
Thanks a lot!
I think you can do something like:
MM.objects.all().values('b', 'a').annotate(max=Max('c'))
Note that you need to import something to use Max: from django.db.models import Max
values('b', 'a')
will give GROUP BY b, a
and annotate(...)
will compute the MAX in your query.
这篇关于Django ORM查询GROUP BY多列组合MAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!