aggregate() & annotate() (Django)

aggregate() computes a single summary value over a QuerySet (like a total or average), while annotate() adds a computed value to each object (like each author's post count). Both push the math into the database.

Django

These methods bring SQL's GROUP BY and aggregate functions (Count, Sum, Avg, Max, Min) into the ORM. aggregate() collapses the whole QuerySet into one dict of results: Order.objects.aggregate(total=Sum('amount')). It returns numbers, not objects.

annotate() instead attaches an aggregate to each row, typically after grouping by a relationship. Author.objects.annotate(num_posts=Count('post')) gives every author an extra num_posts attribute, computed by the database. You can then filter or order by the annotation.

The mental rule: aggregate() = one summary for the whole queryset; annotate() = one extra value per object. Both are far more efficient than counting or summing in a Python loop.

Syntax

qs.aggregate(total=Sum("amount"))
qs.annotate(n=Count("items"))

Examples

Python

from django.db.models import Count, Sum, Avg

# one summary value
Order.objects.aggregate(total=Sum("amount"), avg=Avg("amount"))

# a value per object, then order by it
authors = (Author.objects
           .annotate(num_posts=Count("post"))
           .order_by("-num_posts"))

Learn it in a lesson

See also

Back to the Dictionary