Django annotate vs aggregate, and Subquery with OuterRef

Django Interview Q&A November 13, 2026 python

aggregate returns a dict of overall values.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# ======================================================================
# Q: What is the difference between annotate and aggregate in Django, and what
# are Subquery and OuterRef for?
#
# aggregate returns a dict of overall values. annotate adds a computed field to
# every row. Subquery/OuterRef allows correlated subqueries, e.g. "the latest
# price of each product", without N+1:
# ======================================================================

latest = Price.objects.filter(product=OuterRef('pk')).order_by('-created')
Product.objects.annotate(last_price=Subquery(latest.values('amount')[:1]))