Django ORM查询GROUP BY多列组合MAX [英] Django ORM query GROUP BY multiple columns combined by MAX

查看:1400
本文介绍了Django ORM查询GROUP BY多列组合MAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django与MySQL。我有一个类似于以下的模型:

 类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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆