Short answer: use aggregate() when you want one summary for a whole queryset, such as the average order value: Django runs the calculation in the database and returns a plain dict. Use annotate() when you want a value for each object or each group, such as the number of orders per product: it adds the value as an extra field, and you still have a queryset to filter, sort and slice. Both take the same functions (Count, Sum, Avg, Min and Max) from django.db.models.
Tested with Django 5.2.19 and Python 3.12.16 on 17 November 2026, on PostgreSQL 17.11 and SQLite 3.53.1.
Aggregation lets the database compute counts, sums, averages, minimums and maximums for you, instead of pulling every row into Python and looping over it. On a large table that is the difference between one fast query and thousands of objects loaded into memory. In one line: aggregate() collapses a queryset to one row of numbers; annotate() adds a per-row (or per-group) number and stays a queryset.
This guide covers both, plus grouping with values().annotate(), conditional aggregation, distinct counts, the JOIN-inflation bug that silently inflates your numbers, F() expressions inside aggregates, filtering before and after annotation, and the results that differ between SQLite and PostgreSQL. Every output shown is the real PostgreSQL output for the sample data below.
The example models
Every query below runs against this small e-commerce schema: stores, the products they sell, and the orders placed for those products.
# shop/models.py
from django.db import models
class Store(models.Model):
name = models.CharField(max_length=120)
city = models.CharField(max_length=80)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=120)
store = models.ForeignKey(Store, on_delete=models.CASCADE, related_name="products")
price = models.DecimalField(max_digits=10, decimal_places=2)
in_stock = models.BooleanField(default=True)
def __str__(self):
return self.name
class Order(models.Model):
PENDING, PAID, REFUNDED = "pending", "paid", "refunded"
STATUS_CHOICES = [(PENDING, "Pending"), (PAID, "Paid"), (REFUNDED, "Refunded")]
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="orders")
quantity = models.PositiveIntegerField(default=1)
total = models.DecimalField(max_digits=10, decimal_places=2)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default=PENDING)
created_at = models.DateTimeField(auto_now_add=True)Sample data
Run makemigrations and migrate, then paste this into python manage.py shell to get the same numbers as the examples. It is deliberately small: four stores (one with no products), five products (one with no orders, and two at the same price) and nine orders. That is enough to show every gotcha in this guide.
# Sample data: paste into `python manage.py shell` after migrating
from decimal import Decimal as D
from shop.models import Store, Product, Order
gadget = Store.objects.create(name="Gadget Hub", city="Hyderabad")
byte = Store.objects.create(name="Byte Bazaar", city="Bengaluru")
circuit = Store.objects.create(name="Circuit Corner", city="Hyderabad")
Store.objects.create(name="Desk Depot", city="Chennai") # no products, no orders
mouse = Product.objects.create(name="Wireless Mouse", store=gadget, price=D("25.00"))
hub = Product.objects.create(name="USB-C Hub", store=gadget, price=D("25.00")) # no orders yet
keyboard = Product.objects.create(name="Mechanical Keyboard", store=gadget, price=D("90.00"))
monitor = Product.objects.create(name="27-inch Monitor", store=byte, price=D("300.00"))
webcam = Product.objects.create(name="HD Webcam", store=circuit, price=D("60.00"))
for product, quantity, total, status in [
(mouse, 2, "50.00", "paid"),
(mouse, 1, "25.00", "paid"),
(mouse, 1, "25.00", "pending"),
(keyboard, 1, "90.00", "paid"),
(keyboard, 1, "81.00", "paid"), # sold at a 10% discount
(monitor, 1, "300.00", "paid"),
(monitor, 2, "570.00", "paid"), # 30.00 off for two
(monitor, 1, "300.00", "refunded"),
(webcam, 1, "60.00", "refunded"),
]:
Order.objects.create(product=product, quantity=quantity, total=D(total), status=status)aggregate(): one summary value over a queryset
Call aggregate() at the end of any queryset. Pass it one or more aggregate functions and it returns a single dictionary. Filters applied before aggregate() scope the calculation, so you can summarise a subset just as easily as the whole table.
>>> from django.db.models import Count, Sum, Avg, Min, Max
>>> from shop.models import Store, Product, Order
# Whole-table summaries
>>> Product.objects.aggregate(Avg("price"))
{'price__avg': Decimal('100.0000000000000000')}
>>> Product.objects.aggregate(Max("price"), Min("price"))
{'price__max': Decimal('300.00'), 'price__min': Decimal('25.00')}
# Several aggregates at once, with your own keys
>>> Order.objects.aggregate(
... orders=Count("id"),
... revenue=Sum("total"),
... avg_order=Avg("total"),
... )
{'orders': 9, 'revenue': Decimal('1501.00'), 'avg_order': Decimal('166.7777777777777778')}
# Filter first to scope the summary
>>> Order.objects.filter(status=Order.PAID).aggregate(paid_revenue=Sum("total"))
{'paid_revenue': Decimal('1116.00')}By default the output key is <field>__<function> (for example price__avg). Supply your own keyword name when you want a cleaner key or are running several aggregates of the same type.
Two things to watch in the output. On PostgreSQL, Avg of a DecimalField comes back with 16 decimal places, as above, so round it in the database with Round(..., 2). And Sum, Avg, Min and Max return None (not 0) when no rows match, so guard against None or pass default=0 (available since Django 4.0):
# No order has 10 or more items, so there is nothing to sum
>>> Order.objects.filter(quantity__gte=10).aggregate(Sum("total"))
{'total__sum': None}
>>> Order.objects.filter(quantity__gte=10).aggregate(Sum("total", default=0))
{'total__sum': Decimal('0')}
# Round in the database instead of formatting in Python
>>> from django.db.models.functions import Round
>>> Order.objects.aggregate(avg_order=Round(Avg("total"), 2))
{'avg_order': Decimal('166.78')}The built-in aggregate functions
| Function | Returns | No matching rows | Typical use |
|---|---|---|---|
Count(field) |
Number of rows (or related rows) | 0 |
How many orders or products |
Sum(field) |
Total of a numeric column | None (or default) |
Revenue, total quantity |
Avg(field) |
Mean of a numeric column | None (or default) |
Average order value |
Min(field) |
Smallest value | None (or default) |
Cheapest product, earliest date |
Max(field) |
Largest value | None (or default) |
Most expensive product, latest date |
StdDev and Variance work the same way. Count, Sum and Avg accept distinct=True (Min and Max raise TypeError if you pass it), and every function accepts a filter=Q(...) argument, covered below. All of them live in django.db.models.
Django 5.2 is stricter about aggregate arguments
From Django 5.2, Avg, Count, Max, Min, StdDev, Sum and Variance take exactly one expression and raise TypeError straight away if you pass more. Older versions sent the extra argument on to the database. There it failed with a confusing error or, worse, ran something else: SQLite has two-argument scalar MAX() and MIN() functions, so on Django 5.1.15 Order.objects.aggregate(x=Max("total", "quantity", output_field=DecimalField())) returned 50 in our test, when the largest order total is 570. If you are still on Django 4.2 or older, our Django 4.2 to 5.2 upgrade guide covers this and the other changes on the way.
# Django 5.2: each aggregate takes exactly one expression
>>> Order.objects.aggregate(Sum("total", "quantity"))
Traceback (most recent call last):
...
TypeError: 'Sum' takes exactly 1 argument (2 given)
# One aggregate per column instead
>>> Order.objects.aggregate(Sum("total"), Sum("quantity"))
{'total__sum': Decimal('1501.00'), 'quantity__sum': 11}annotate(): per-object and per-group values (GROUP BY)
annotate() adds a calculated attribute to each row of the queryset and keeps the queryset alive, so you can filter, order and slice the result. Annotating across a reverse relation gives you a per-object count. Objects with no related rows get 0 rather than disappearing, because Django uses a LEFT OUTER JOIN.
# How many orders does each product have? (per-object annotation)
>>> products = Product.objects.annotate(order_count=Count("orders")).order_by("name")
>>> for p in products:
... print(p.name, p.order_count)
27-inch Monitor 3
HD Webcam 1
Mechanical Keyboard 2
USB-C Hub 0
Wireless Mouse 3
# The annotation is a real queryset field: order and slice by it
>>> Product.objects.annotate(order_count=Count("orders")).order_by("-order_count", "name")[:3]
<QuerySet [<Product: 27-inch Monitor>, <Product: Wireless Mouse>, <Product: Mechanical Keyboard>]>Grouping with values().annotate()
To produce a true SQL GROUP BY over a column (rather than per object), chain values() before annotate(). The fields in values() become the grouping columns, and the aggregate is computed once per distinct group. To see the SQL Django runs, print the queryset's query attribute. Django 5.2 refers to the grouped and sorted columns by position, so GROUP BY 1 below is the city.
# Order count and revenue per store city (GROUP BY city)
>>> by_city = (
... Order.objects
... .values("product__store__city")
... .annotate(orders=Count("id"), revenue=Sum("total"))
... .order_by("-revenue")
... )
>>> for row in by_city:
... print(row)
{'product__store__city': 'Bengaluru', 'orders': 3, 'revenue': Decimal('1170.00')}
{'product__store__city': 'Hyderabad', 'orders': 6, 'revenue': Decimal('331.00')}
# print(by_city.query) shows the SQL. On PostgreSQL, shortened:
# SELECT "shop_store"."city" AS "product__store__city",
# COUNT("shop_order"."id") AS "orders",
# SUM("shop_order"."total") AS "revenue"
# FROM "shop_order"
# INNER JOIN "shop_product" ON (...) INNER JOIN "shop_store" ON (...)
# GROUP BY 1 ORDER BY 3 DESC
# Reversed, annotate() runs per order and values() only picks a column:
# nine rows, one per order, instead of two groups
>>> Order.objects.annotate(revenue=Sum("total")).values("product__store__city").count()
9The order of clauses matters. values("product__store__city").annotate(...) groups by city. If you reverse it to annotate(...).values(...), Django annotates per object first and values() only selects columns, so you get one row per order. Put values() before annotate() whenever you mean "group by".
Conditional aggregation
Conditional aggregation answers "count or sum only the rows matching a condition" in a single query, instead of running one query per status. The modern way is the filter argument that every aggregate accepts. On PostgreSQL and SQLite, Django turns it into SQL FILTER (WHERE ...); on databases without FILTER, such as MySQL, it writes an equivalent CASE expression.
>>> from django.db.models import Count, Sum, Q
# Per-status counts in ONE query
>>> Order.objects.aggregate(
... paid=Count("id", filter=Q(status="paid")),
... pending=Count("id", filter=Q(status="pending")),
... refunded=Count("id", filter=Q(status="refunded")),
... )
{'paid': 6, 'pending': 1, 'refunded': 2}
# Mix conditional and unconditional aggregates per object
>>> products = Product.objects.annotate(
... total_orders=Count("orders"),
... paid_orders=Count("orders", filter=Q(orders__status="paid")),
... paid_revenue=Sum("orders__total", filter=Q(orders__status="paid"), default=0),
... ).order_by("name")
>>> for p in products:
... print(p.name, p.total_orders, p.paid_orders, p.paid_revenue)
27-inch Monitor 3 2 870.00
HD Webcam 1 0 0
Mechanical Keyboard 2 2 171.00
USB-C Hub 0 0 0
Wireless Mouse 3 2 75.00The older Case(When(...)) form
Before the filter argument existed, the same effect was achieved by summing a Case/When expression. It still works, and you still need it when the value being aggregated depends on the condition, such as a commission rate that changes with the order size.
>>> from decimal import Decimal
>>> from django.db.models import Sum, Case, When, Value, F, IntegerField, DecimalField
# Equivalent of the paid count above, the explicit way
>>> Order.objects.aggregate(
... paid=Sum(Case(When(status="paid", then=1), default=0, output_field=IntegerField())),
... )
{'paid': 6}
# Conditional VALUE, not just a count: commission of 10% on paid
# orders of 100 or more, and 5% on smaller paid orders
>>> Order.objects.aggregate(
... commission=Sum(Case(
... When(status="paid", total__gte=100, then=F("total") * Decimal("0.10")),
... When(status="paid", then=F("total") * Decimal("0.05")),
... default=Value(0),
... output_field=DecimalField(max_digits=12, decimal_places=2),
... )),
... )
{'commission': Decimal('99.3000')}When clauses are checked in order and the first match wins, so the second one needs no upper limit. Note the output, too: output_field sets the type but does not round, and PostgreSQL kept the four decimal places of the multiplication (99.3000). Wrap the Sum in Round(..., 2) if you display it.
Reach for filter=Q(...) for conditional counts and sums of an existing field (it is shorter and reads better). Reach for Case(When(...)) when the value being aggregated changes with the condition.
Counting correctly: distinct=True and the JOIN-inflation gotcha
This is the most common aggregation bug in Django. When one query aggregates across a multi-valued relation and also aggregates something else, the SQL JOIN repeats rows, and your counts and sums come out too high, with no error.
Gadget Hub has 3 products and 5 orders. Counting both in one query joins each product to its orders. That gives one row per order, plus one for the USB-C Hub, which has none, so the product count sees 6 rows. Also, name annotations so they do not clash with a field or relation: calling the first one products raises ValueError: The annotation 'products' conflicts with a field on the model.
# WRONG: the product count is inflated by the JOIN to orders
>>> from django.db.models import Count
>>> stores = Store.objects.annotate(
... product_count=Count("products"),
... order_count=Count("products__orders"),
... ).order_by("name")
>>> for s in stores:
... print(s.name, s.product_count, s.order_count)
Byte Bazaar 3 3
Circuit Corner 1 1
Desk Depot 0 0
Gadget Hub 6 5
# RIGHT: distinct=True counts each product once
>>> stores = Store.objects.annotate(
... product_count=Count("products", distinct=True),
... order_count=Count("products__orders", distinct=True),
... ).order_by("name")
>>> for s in stores:
... print(s.name, s.product_count, s.order_count)
Byte Bazaar 1 3
Circuit Corner 1 1
Desk Depot 0 0
Gadget Hub 3 5distinct=True fixes counts, but not sums. Sum and Avg accept distinct=True too, but it removes duplicate values, not duplicate rows: Gadget Hub sells two products at 25.00, so a distinct sum counts that price once. The robust fix is to compute each aggregate in its own Subquery, so the relations are never joined together in one query. Below, "catalogue value" is the sum of a store's product prices: 300.00 for Byte Bazaar and 140.00 for Gadget Hub.
# WRONG: each product's price is added once per order row
>>> from django.db.models import Count, Sum
>>> stores = Store.objects.annotate(
... order_count=Count("products__orders"),
... catalogue_value=Sum("products__price"),
... ).order_by("name")
>>> for s in stores:
... print(s.name, s.order_count, s.catalogue_value)
Byte Bazaar 3 900.00
Circuit Corner 1 60.00
Desk Depot 0 None
Gadget Hub 5 280.00
# ALSO WRONG: distinct=True drops one of the two 25.00 products
>>> stores = Store.objects.annotate(
... order_count=Count("products__orders"),
... catalogue_value=Sum("products__price", distinct=True),
... ).order_by("name")
>>> for s in stores:
... print(s.name, s.order_count, s.catalogue_value)
Byte Bazaar 3 300.00
Circuit Corner 1 60.00
Desk Depot 0 None
Gadget Hub 5 115.00
# RIGHT: one subquery per aggregate, so nothing is joined twice
>>> from decimal import Decimal
>>> from django.db.models import OuterRef, Subquery
>>> from django.db.models.functions import Coalesce
>>> order_count = (
... Order.objects.filter(product__store=OuterRef("pk"))
... .order_by().values("product__store")
... .annotate(c=Count("id")).values("c")
... )
>>> catalogue_value = (
... Product.objects.filter(store=OuterRef("pk"))
... .order_by().values("store")
... .annotate(v=Sum("price")).values("v")
... )
>>> stores = Store.objects.annotate(
... order_count=Coalesce(Subquery(order_count), 0),
... catalogue_value=Coalesce(Subquery(catalogue_value), Decimal("0")),
... ).order_by("name")
>>> for s in stores:
... print(s.name, s.order_count, s.catalogue_value)
Byte Bazaar 3 300.00
Circuit Corner 1 60.00
Desk Depot 0 0
Gadget Hub 5 140.00Two details in the subquery version matter:
- The empty
.order_by(). Since Django 3.1, a model'sMeta.orderingis left out ofGROUP BYqueries. But an explicit ordering (from a custom manager, or a queryset built elsewhere) still adds its columns to the subquery'sGROUP BYand breaks the grouping. In our test, ordering the order subquery bycreated_atmade SQLite silently return 1 instead of 5 for Gadget Hub, and made PostgreSQL raise "more than one row returned by a subquery used as an expression"..order_by()clears any ordering. - The fallback type in
Coalesce. It must match the subquery's type.Coalesce(Subquery(catalogue_value), 0)raisesFieldError: Expression contains mixed types: DecimalField, IntegerField. You must set output_field., so useDecimal("0")for decimal sums.Subqueryworks out its own output type from the inner.values(), so it needs nooutput_field.
distinct=True to count unique values
Count with distinct=True also counts unique values of a column, which is the ORM equivalent of COUNT(DISTINCT col).
# In how many cities have our stores taken orders?
>>> Order.objects.aggregate(cities=Count("product__store__city", distinct=True))
{'cities': 2}F() expressions inside aggregates
F() references a column, or an expression built from columns, at the database level. Combined with an aggregate, it lets you sum or average a derived value without loading rows into Python. That includes values that span a relation, such as an order's quantity times its product's price.
>>> from django.db.models import F, Sum, Avg
>>> from django.db.models.functions import Round
# List value (quantity times current price) against what was charged
>>> Order.objects.aggregate(
... list_value=Sum(F("quantity") * F("product__price")),
... charged=Sum("total"),
... )
{'list_value': Decimal('1540.00'), 'charged': Decimal('1501.00')}
# The discount given, as one expression
>>> Order.objects.aggregate(discount=Sum(F("quantity") * F("product__price") - F("total")))
{'discount': Decimal('39.00')}
# Average price actually paid per item, for each product
>>> products = Product.objects.annotate(
... avg_paid=Round(Avg(F("orders__total") / F("orders__quantity")), 2),
... ).order_by("name")
>>> for p in products:
... print(p.name, p.avg_paid)
27-inch Monitor 295.00
HD Webcam 60.00
Mechanical Keyboard 85.50
USB-C Hub None
Wireless Mouse 25.00Django 5.2 works out the output type of most arithmetic itself: an integer field times a decimal field gives a decimal, as above. When it cannot, it raises FieldError: Expression contains mixed types and you pass an explicit output_field, as in the Case example. For deeper query-tuning patterns like this, see our guide on Django database access optimization.
Filtering and ordering aggregated results
There are two distinct places to filter, and they map to SQL WHERE vs HAVING:
.filter()beforeannotate()restricts which rows feed the aggregate (SQLWHERE). "Count only this month's paid orders.".filter()on the annotation afterannotate()restricts which objects or groups survive (SQLHAVING). "Keep only products with more than five orders."
You can use both together, and you can order_by() an annotated field directly. If you only need the aggregate to filter on, alias() (Django 3.2 and newer) works like annotate() without adding the value to the results.
>>> from datetime import timedelta
>>> from django.db.models import Count, Sum, Q
>>> from django.utils import timezone
# Count only paid orders per product
>>> qs = Product.objects.annotate(
... paid_orders=Count("orders", filter=Q(orders__status="paid")),
... )
# HAVING: keep products with 2 or more paid orders, best sellers first
>>> qs.filter(paid_orders__gte=2).order_by("-paid_orders", "name")
<QuerySet [<Product: 27-inch Monitor>, <Product: Mechanical Keyboard>, <Product: Wireless Mouse>]>
# WHERE, then GROUP BY, then HAVING, in one query
>>> month_ago = timezone.now() - timedelta(days=30)
>>> (
... Order.objects.filter(created_at__gte=month_ago, status="paid") # WHERE
... .values("product__store__city")
... .annotate(revenue=Sum("total"))
... .filter(revenue__gte=500) # HAVING
... .order_by("-revenue")
... )
<QuerySet [{'product__store__city': 'Bengaluru', 'revenue': Decimal('870.00')}]>
# Filter on an aggregate without returning it: alias() instead of annotate()
>>> Product.objects.alias(n=Count("orders")).filter(n__gte=3).order_by("name")
<QuerySet [<Product: 27-inch Monitor>, <Product: Wireless Mouse>]>The order of filter() and annotate() changes the numbers
A filter on a related field gives different answers depending on where it goes. With filter= inside the aggregate, every product stays and the ones without a match show 0. With .filter() before annotate(), products without a paid order drop out of the results. With .filter() on the relation after annotate(), Django adds a second JOIN for the filter and the count is multiplied: the 27-inch Monitor has 3 orders, 2 of them paid, and comes out as 6.
# filter= inside the aggregate: all five products stay, with 0 where none match
>>> Product.objects.annotate(paid=Count("orders", filter=Q(orders__status="paid"))).count()
5
# filter() BEFORE annotate(): products without a paid order drop out
>>> qs = Product.objects.filter(orders__status="paid").annotate(paid=Count("orders"))
>>> for p in qs.order_by("name"):
... print(p.name, p.paid)
27-inch Monitor 2
Mechanical Keyboard 2
Wireless Mouse 2
# filter() on the relation AFTER annotate(): a second JOIN inflates the count
>>> qs = Product.objects.annotate(n=Count("orders")).filter(orders__status="paid")
>>> for p in qs.order_by("name"):
... print(p.name, p.n)
27-inch Monitor 6
Mechanical Keyboard 4
Wireless Mouse 6aggregate() vs annotate() at a glance
aggregate() |
annotate() |
|
|---|---|---|
| Returns | A single dict of summary values |
A queryset with an extra field per object or group |
| Scope | The whole queryset, collapsed to one row | Per object, or per group with values() |
| Chainable? | No: it is terminal | Yes: filter, order or slice the result |
| SQL it maps to | A bare SELECT COUNT/SUM/... |
SELECT ..., AGG(...) ... GROUP BY ... |
| Use when | You need one overall number | You need a number for each row or group |
A handy rule: if the answer is "one number," use aggregate(); if the answer is "a number per something," use annotate().
Aggregating over related models
Aggregates follow relationships with the usual double-underscore syntax, in both directions. Spanning a relation in an aggregate joins the related table, which is why the de-duplication rules above matter once more than one relation is involved. In the second example below, both aggregates follow the same path (one row per order), so neither is inflated and distinct=True is not needed.
# Forward relation: average price of products sold in a given city
>>> Product.objects.filter(store__city="Hyderabad").aggregate(Avg("price"))
{'price__avg': Decimal('50.0000000000000000')}
# Reverse relation: each store's order count and revenue, busiest first.
# default=0 keeps Desk Depot (no orders) at the bottom on every database.
>>> stores = Store.objects.annotate(
... order_count=Count("products__orders"),
... revenue=Sum("products__orders__total", default=0),
... ).order_by("-revenue")
>>> for s in stores:
... print(s.name, s.order_count, s.revenue)
Byte Bazaar 3 1170.00
Gadget Hub 5 271.00
Circuit Corner 1 60.00
Desk Depot 0 0Results that differ between SQLite and PostgreSQL
Many projects develop on SQLite and run PostgreSQL in production. The queries in this guide return the same rows on both, but three differences showed up while testing them:
- Decimal places. PostgreSQL returns sums, minimums and maximums of a
DecimalFieldwith the column's decimal places (Decimal('1501.00')), and averages with 16 decimal places. SQLite has no decimal type: it returnsDecimal('1501'), and arithmetic on decimal columns runs in floating point. The values compare equal in Python, but format them before you display them, and check money calculations on the database you deploy to. - Where
Nonesorts. PostgreSQL putsNULLfirst in a descending sort; SQLite treats it as the smallest value and puts it last. An annotation that isNonefor some rows (aSumwith no matching rows, for example) therefore reorders your "top" lists. Usedefault=0, or say whereNULLgoes withnulls_last=True. - Row order. Without
order_by(), the two databases returned the same annotated rows in different orders. Order explicitly whenever the order matters, including in tests.
>>> from django.db.models import Avg, F, Sum
# Decimal places: PostgreSQL 17 keeps them
>>> Order.objects.aggregate(revenue=Sum("total"), avg_order=Avg("total"))
{'revenue': Decimal('1501.00'), 'avg_order': Decimal('166.7777777777777778')}
# The same query on SQLite 3.53:
# {'revenue': Decimal('1501'), 'avg_order': Decimal('166.777777777778')}
# Where None sorts: PostgreSQL puts the store with no orders first
>>> stores = Store.objects.annotate(revenue=Sum("products__orders__total"))
>>> [s.name for s in stores.order_by("-revenue")]
['Desk Depot', 'Byte Bazaar', 'Gadget Hub', 'Circuit Corner']
# SQLite puts Desk Depot last. Say where NULL goes and both agree:
>>> [s.name for s in stores.order_by(F("revenue").desc(nulls_last=True))]
['Byte Bazaar', 'Gadget Hub', 'Circuit Corner', 'Desk Depot']When conditions get complex, combine aggregates with Q objects (see querying with Django Q objects) and conditional expressions (see Django conditional expression in queries). If a report or dashboard in your own Django app is slow because it counts and sums in Python, our Django development services team can help move that work into the database.
Frequently Asked Questions
What's the difference between aggregate() and annotate() in Django?
aggregate() returns a single dictionary summarising the whole queryset, for example the average price across all products. It is terminal: you can't chain anything after it. annotate() adds a computed value to each object (or each group when you use values().annotate()) and returns a queryset you can keep filtering, ordering and slicing. Use aggregate() for one overall number and annotate() for a number per object or per group.
How do I group by a field in Django?
Chain values() before annotate(). The fields you pass to values() become the GROUP BY columns, and the aggregate is computed once per group. For example, Order.objects.values("status").annotate(revenue=Sum("total")) produces one row per status with its summed total. Put values() first; if you call annotate() before values(), Django annotates per object instead of grouping.
How do I do conditional counts or sums in Django?
Pass a filter argument to the aggregate: Count("id", filter=Q(status="paid")) counts only paid rows, and you can run several such aggregates in one query. Django translates this to SQL FILTER (WHERE ...), or to a CASE expression on databases without FILTER. For conditional values (where the number being aggregated changes per row, not just whether it counts), use Sum(Case(When(...), default=..., output_field=...)).
Why are my aggregated counts or sums too high in Django?
This is JOIN inflation. When a single query aggregates across a multi-valued relation and something else, the SQL join repeats rows, so counts and sums are duplicated. Fix counts with distinct=True (Count("products", distinct=True)). Sum and Avg can't be fixed that way, because distinct=True on them drops duplicate values rather than duplicate rows. Compute each of those in its own Subquery, with OuterRef and an empty .order_by(), so the relations are never joined together in one query.
Can I filter on an annotated value in Django?
Yes. Calling .filter() on the annotation after annotate() maps to SQL HAVING, for example .annotate(n=Count("orders")).filter(n__gt=5) keeps only objects with more than five orders. Calling .filter() before annotate() (or using the filter= argument inside the aggregate) restricts which rows feed the aggregate and maps to SQL WHERE. Use alias() instead of annotate() when you only need the value for filtering.
What does aggregate() return when the queryset is empty?
Count returns 0, but Sum, Avg, Min and Max return None because there is nothing to compute. To get a numeric fallback instead, pass default, for example Sum("total", default=0) (Django 4.0 and newer). If you use Coalesce instead, the fallback must match the field type: Coalesce(Sum("total"), Decimal("0")) works for a DecimalField, while Coalesce(Sum("total"), 0) raises FieldError.
Why does Django 5.2 raise "TypeError: 'Sum' takes exactly 1 argument"?
Since Django 5.2, Avg, Count, Max, Min, StdDev, Sum and Variance accept exactly one expression. Code like Sum("total", "quantity") used to reach the database and fail there or, on SQLite, quietly return a wrong number. Use one aggregate per column, as in aggregate(Sum("total"), Sum("quantity")), or aggregate an expression such as Sum(F("quantity") * F("product__price")).