views:

82

answers:

2
+2  Q: 

Django: Group by?

I'm looking for something like the following:

previous_invoices = Invoice.objects.filter(is_open=False).order_by('-created').group_by('user')

(group_by() doesn't exist)

This would find the most recently closed invoice for each user. This aggregation API seems to let you do stuff like this for counts and sums, but I don't need a count or sum or anything, I actually want the invoice objects!

A: 

http://stackoverflow.com/questions/327807/django-equivalent-for-count-and-group-by/327987#327987

http://docs.djangoproject.com/en/dev/topics/db/aggregation/

Brandon H
"at your own risk, and in full knowledge that the query.group_by attribute is not part of a public API and could change" -- what's the 1.2 way?
Mark
i think you're stuck in this land for now. here's the latest documentation. http://docs.djangoproject.com/en/dev/topics/db/aggregation/
Brandon H
He already linked to that page in the question.
Adriano Varoli Piazza
+1  A: 

There's this page from 2007 who hacked it to django, but that would be moot since pre 1.1 does have an undocumented group_by` anyway. But this thread from a year ago seems to have some insights. Essentially:

Django intentionally does not expose "GROUP BY" or anything like that, in the ORM. Although the fact that we're over a relational storage backend sometimes leaks through, the ORM API is fairly SQL-agnostic. Instead, we expose particular pieces of functionality that happen to be implemented using "GROUP BY" when it's turned into SQL (and could well be implemented by some entirely different set of magical fairies with a different storage system backend).

See also the mentions of using extra, and also the magical ways in which that can fail. Best of luck.

Adriano Varoli Piazza