[Django]-Django queryset and GROUP BY

4👍

There’s no high-level group_by in the queryset. It’s used in calls to aggregate and annotate but it is not available to you.

There’s a low-level API which is not documented at all. You can get an internal query description:

queryset = ... #whatever query you'd want to group by
query = queryset.query

and then you can alter the group_by member -which is a list- by adding a field which you’d want to group by:

query.group_by.append('a_field')

But:

  • you have to seriously know what you’re doing.
  • there’s no guarantee of stability of this API.

The current alternative for this is falling back to a raw (django.db.connection.* methods) SQL query.

Edit: I just saw this 3rd-party application which could help you with reports. I don’t know if you can use in-code reports, or you have to limit yourself to in-view reports (i.e.: don’t know if you can process reports in code or just have them as final results).

Leave a comment