I have often been confused by the way that the Django ORM implements the equivalent of the “group by” statement of SQL. When I want to group some data I often think in a structure very similar to SQL. And because Django has a higher level abstraction I often forget how to string it together properly. In this post, I will describe how I understand the grouping in Django after experimenting a bit with the feature.
Values
Values() is the method that does the grouping of the data. Calling values() without a subsequent annotate() call just pulls out the values of the specified fields.
Calling annotate() after
Annotate
The annotate call defines what information to add to each group.
Order_by
An important quirk is the interaction between
I hope this cleared up how to group data and add annotations with the Django ORM. The official documentation is brilliant as always, so also check that out for more information on aggregation: https://docs.djangoproject.com/en/2.2/topics/db/aggregation/#values