user592419
user592419

Reputation: 5233

Django QuerySet First in Group

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?

Upvotes: 0

Views: 1198

Answers (1)

Kevin Stone
Kevin Stone

Reputation: 8981

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.

Upvotes: 4

Related Questions