TExcelTAD
Home › Django › Django Aggregation & Annotation

Django Aggregation & Annotation

So far every query returned rows. Often you need summaries instead: the total revenue, the average rating, the number of books per author. Django has two tools for that:

Method Returns SQL idea
aggregate(...) one dictionary summarising the whole QuerySet SELECT SUM(price) FROM …
annotate(...) the QuerySet, with an extra value on every row SELECT …, COUNT(book.id) … GROUP BY author.id

The aggregate functions live in django.db.models: Count, Sum, Avg, Min, Max, StdDev and Variance.

aggregate(): one summary for the whole set

python · try it yourself
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
from django.db.models import Count, Sum, Avg, Min, Max

class Sale(models.Model):
    product = models.CharField(max_length=30)
    region = models.CharField(max_length=10)
    amount = models.IntegerField()
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Sale)
Sale.objects.bulk_create([Sale(product=p, region=r, amount=a) for p, r, a in [
    ("Tea", "north", 120), ("Tea", "south", 80), ("Coffee", "north", 200),
    ("Coffee", "south", 150), ("Juice", "north", 50)]])

print(Sale.objects.aggregate(Sum("amount")))
print(Sale.objects.aggregate(total=Sum("amount"), average=Avg("amount"),
                             smallest=Min("amount"), largest=Max("amount"), n=Count("id")))
print(Sale.objects.filter(region="north").aggregate(north_total=Sum("amount")))
print(Sale.objects.filter(region="west").aggregate(west_total=Sum("amount")))
{'amount__sum': 600}
{'total': 600, 'average': 120.0, 'smallest': 50, 'largest': 200, 'n': 5}
{'north_total': 370}
{'west_total': None}

Without a name, the key is <field>__<function>. Note that summing no rows gives None, not 0 — pass default=0 (Sum("amount", default=0)) when you want a number.

GROUP BY with values() + annotate()

Calling values("field") before annotate() groups the rows by that field — the ORM's version of SQL's GROUP BY:

python · try it yourself
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
from django.db.models import Count, Sum

class Sale(models.Model):
    product = models.CharField(max_length=30)
    region = models.CharField(max_length=10)
    amount = models.IntegerField()
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Sale)
Sale.objects.bulk_create([Sale(product=p, region=r, amount=a) for p, r, a in [
    ("Tea", "north", 120), ("Tea", "south", 80), ("Coffee", "north", 200),
    ("Coffee", "south", 150), ("Juice", "north", 50)]])

per_product = (Sale.objects.values("product")
               .annotate(total=Sum("amount"), sales=Count("id"))
               .order_by("-total"))
for row in per_product:
    print(row)

print("---")
big = (Sale.objects.values("region").annotate(total=Sum("amount"))
       .filter(total__gt=300).order_by("region"))
print(list(big))
{'product': 'Coffee', 'total': 350, 'sales': 2}
{'product': 'Tea', 'total': 200, 'sales': 2}
{'product': 'Juice', 'total': 50, 'sales': 1}
---
[{'region': 'north', 'total': 370}]

Filtering after annotate() on the annotated value becomes SQL's HAVING clause.

annotate() across relationships

The most common use of annotate() is counting or summing related rows: books per author, comments per post. Relationship names (like books below) work inside aggregate functions:

python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["demo"] = types.ModuleType("demo")      # stand-in for a demo/ app package
sys.modules["demo"].__file__ = "demo/__init__.py"
settings.configure(INSTALLED_APPS=["demo"],
                   DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
from django.db.models import Count, Avg, Max

class Author(models.Model):
    name = models.CharField(max_length=30)
    class Meta:
        app_label = "demo"

class Book(models.Model):
    title = models.CharField(max_length=50)
    rating = models.IntegerField()
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books")
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Author)
    editor.create_model(Book)

le_guin = Author.objects.create(name="Le Guin")
herbert = Author.objects.create(name="Herbert")
Author.objects.create(name="Newcomer")
Book.objects.create(title="A Wizard of Earthsea", rating=5, author=le_guin)
Book.objects.create(title="The Dispossessed", rating=4, author=le_guin)
Book.objects.create(title="The Left Hand of Darkness", rating=5, author=le_guin)
Book.objects.create(title="Dune", rating=5, author=herbert)
Book.objects.create(title="Dune Messiah", rating=3, author=herbert)

authors = Author.objects.annotate(
    num_books=Count("books"), avg_rating=Avg("books__rating"), best=Max("books__rating")
).order_by("-num_books", "name")

for a in authors:
    print(f"{a.name:<9} books={a.num_books} avg={a.avg_rating} best={a.best}")

print([a.name for a in Author.objects.annotate(n=Count("books")).filter(n__gte=2).order_by("name")])
Le Guin   books=3 avg=4.666666666666667 best=5
Herbert   books=2 avg=4.0 best=5
Newcomer  books=0 avg=None best=None
['Herbert', 'Le Guin']

Each Author object now carries num_books, avg_rating and best as ordinary attributes. Authors without books still appear, with a count of 0 (Django uses a LEFT OUTER JOIN).

Conditional aggregation

Pass filter=Q(...) to an aggregate to count or sum only some of the rows — several different counts in a single query:

python · try it yourself
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
from django.db.models import Count, Sum, Q

class Order(models.Model):
    status = models.CharField(max_length=10)
    total = models.IntegerField()
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Order)
Order.objects.bulk_create([Order(status=s, total=t) for s, t in [
    ("paid", 40), ("paid", 25), ("pending", 60), ("cancelled", 15), ("paid", 35)]])

stats = Order.objects.aggregate(
    orders=Count("id"),
    paid=Count("id", filter=Q(status="paid")),
    pending=Count("id", filter=Q(status="pending")),
    revenue=Sum("total", filter=Q(status="paid"), default=0),
    refunds=Sum("total", filter=Q(status="refunded"), default=0),
)
print(stats)
{'orders': 5, 'paid': 3, 'pending': 1, 'revenue': 100, 'refunds': 0}

Tip: Want to see the SQL behind an annotation? Print str(queryset.query) — you'll find the GROUP BY and LEFT OUTER JOIN that Django generated.

Test yourself

What does Sale.objects.aggregate(Sum("amount")) return?

  1. A QuerySet
  2. An integer
  3. A dictionary like {'amount__sum': 600}
  4. A list

How do you get the number of books for each author?

  1. Author.objects.aggregate(Count("books"))
  2. Author.objects.annotate(n=Count("books"))
  3. Book.objects.count()
  4. Author.objects.count("books")

What does Sum("amount") return when no rows match?

  1. 0
  2. None (unless default is given)
  3. An exception
  4. An empty list