What's the difference between `annotate()` and `aggregate()`?
The difference between Django annotate and aggregate for reporting queries, shown through the SQL each produces. aggregate is terminal: it compiles the queryset filters into a SELECT of aggregate functions, runs immediately, and returns a plain dict with no GROUP BY because the whole set is one group. annotate is chainable: it adds the expression to the SELECT list and returns a queryset whose rows are still model instances carrying one extra attribute, adding a LEFT OUTER JOIN and a GROUP BY on the model's own columns when the aggregate crosses a relation, so a parent with no children still appears with a count of zero. Explains why filtering on an annotated value compiles to HAVING rather than WHERE, and demonstrates the trap where two aggregates over two relations in one annotate call produce a row per combination so both counts return the product, with distinct=True as the fix. Includes runnable Django code and real output.
Comentarii