问题
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