Django ORM:Group by和Max [英] Django ORM: Group by and Max
本文介绍了Django ORM:Group by和Max的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的模型:
请求:user,req_time,req_text
$在数据库中,记录可以如下所示: id,user_id,req_time,req_text
1 1 TIMESTAMP YES
2 1 TIMESTAMP NO
3 2 TIMESTAMP YES
/ pre>
等。
如何编写一个Django ORM查询:按用户分组请求,基于req_text过滤请求,还可以选择最终结果集的最大值。所以对于每个用户,我将返回一行与过滤条件匹配,并且也有最大的id。
解决方案
from django.db.models.aggregates import Max
request_values = Requests.objects.filter(req_text ='YES')\
.values('user')\
.annotate(max_id = Max('id'))
I have a model that looks like this:
Requests: user, req_time, req_text
In the DB, the records can look like this:
id, user_id, req_time, req_text
1 1 TIMESTAMP YES
2 1 TIMESTAMP NO
3 2 TIMESTAMP YES
etc.
How do I write a Django ORM query that: groups the Requests by user, filters the Requests based on req_text, and also, select the max id of the resulting result set. So for each user, I will return one row which matches the filter condition and also has the greatest id.
解决方案 from django.db.models.aggregates import Max
request_values = Requests.objects.filter(req_text='YES') \
.values('user') \
.annotate(max_id=Max('id'))
这篇关于Django ORM:Group by和Max的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文