Difference between Django's annotate and aggregate methods?

Alexander Artemenko picture Alexander Artemenko · Nov 2, 2011 · Viewed 32.9k times · Source

Django's QuerySet has two methods, annotate and aggregate. The documentation says that:

Unlike aggregate(), annotate() is not a terminal clause. The output of the annotate() clause is a QuerySet.

Is there any other difference between them? If not, then why does aggregate exist?

Answer

Alasdair picture Alasdair · Nov 2, 2011

I would focus on the example queries rather than your quote from the documentation. Aggregate calculates values for the entire queryset. Annotate calculates summary values for each item in the queryset.

Aggregation

>>> Book.objects.aggregate(average_price=Avg('price'))
{'average_price': 34.35}

Returns a dictionary containing the average price of all books in the queryset.

Annotation

>>> q = Book.objects.annotate(num_authors=Count('authors'))
>>> q[0].num_authors
2
>>> q[1].num_authors
1

q is the queryset of books, but each book has been annotated with the number of authors.