Django ORM: Group by and Max

吃可爱长大的小学妹 提交于 2019-11-27 14:44:46

问题


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.


回答1:


from django.db.models.aggregates import Max

request_values = Requests.objects.filter(req_text='YES') \
                 .values('user') \
                 .annotate(max_id=Max('id'))

Then request_values will look like this:

[
    {'user': 1, 'max_id': 1},
    {'user': 2, 'max_id': 4},
    {'user': 3, 'max_id': 5},
    {'user': 4, 'max_id': 12},
    ...
]


来源:https://stackoverflow.com/questions/6940255/django-orm-group-by-and-max

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!