Django QuerySet First in Group

ε祈祈猫儿з 提交于 2020-01-06 12:43:30

问题


I have a queryset that looks like:

{id, group_id, date}

For each group, keyed by the group_id, I'd like to return the id with the earliest date. How would I do that in a django query? Or is it more efficient to order_by date and then use a python dict to ignore all elements with the same group_id after the first?


回答1:


Django doesn't really have the GROUP BY operator. You could try to mimic it with ordering and distinct().

Try something like this:

queryset.order_by('group_id', 'date').distinct('group_id')

Note: that the group_id has to be first in the ordering to perform the distinct() operation.



来源:https://stackoverflow.com/questions/20806345/django-queryset-first-in-group

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