You fixed the N+1 query problem with prefetch_related, then a routine refactor accidentally removed it — and production got slow again without anyone noticing. assertNumQueries is Django’s built-in TestCase tool: it counts exactly how many queries run inside a block of code, letting you “pin” an endpoint’s query count right in your tests. From now on, anyone who adds even a single query gets a red CI build immediately. This technique fits best with list pages and APIs that return many records with related objects.

The Problem

A familiar scenario: an order list page, each row showing the number of items in the order:

# views.py
def order_list(request):
orders = Order.objects.all() # missing prefetch -> N+1
return render(request, "orders/list.html", {"orders": orders})

The template:

{% for order in orders %}
<p>{{ order.code }} — {{ order.items.count }} items</p>
{% endfor %}

With 10 orders, this view runs 11 queries: 1 to fetch the orders, plus 10 to count items — a textbook N+1 (measured with CaptureQueriesContext on Django 6.1.2). Worse: you fix it with prefetch_related, and months later a colleague refactors the view and accidentally drops the prefetch line. No test complains, and the N+1 silently returns to production.

The Fix

Step 1 — measure the current query count so you know where you stand:

from django.db import connection
from django.test.utils import CaptureQueriesContext
with CaptureQueriesContext(connection) as ctx:
response = self.client.get("/orders/")
print(len(ctx)) # -> 11 with 10 orders: a confirmed N+1

Step 2 — fix it with prefetch_related, then “pin” the query count with assertNumQueries:

# views.py (fixed)
def order_list(request):
orders = Order.objects.prefetch_related("items")
return render(request, "orders/list.html", {"orders": orders})
# tests.py
from django.test import TestCase
class OrderListQueryTest(TestCase):
def test_no_n_plus_1(self):
with self.assertNumQueries(2): # 1 query for orders + 1 prefetch for items
response = self.client.get("/orders/")
self.assertEqual(response.status_code, 200)

Why does this work? assertNumQueries counts every database query inside the with block — even when DEBUG = False (it enables query logging on its own). After the fix, the page runs exactly 2 queries: 1 for orders, 1 for the item prefetch. From now on, anyone who accidentally removes prefetch_related or adds a stray query breaks this test immediately, and CI stops the code before it reaches production. The test above was run for real and passed on Django 6.1.2.

Apply It to Your Project

  • Start with your 3–5 heaviest endpoints: list pages, list APIs with nested serializers, statistics dashboards. Measure with CaptureQueriesContext first, fix the N+1, and only then pin the number into assertNumQueries — never guess the number.
  • The count includes queries from middleware or sessions if they touch the database, so always measure in the real test context (anonymous or logged in). Run CI with the same database type as production to avoid skew from system queries.
  • When a legitimate refactor increases the count: update the number and note the reason right in the test. The number is a “guard rail”, not a sacred constant.

Related Posts

  • Django: Fix N+1 Queries with select_related in 5 Minutes
  • Django: Fix N+1 Queries with prefetch_related for ManyToMany and Reverse Relations
  • Django: Catch Slow and Redundant Queries with django-debug-toolbar in 5 Minutes

FAQ

Does assertNumQueries require DEBUG = True?

No. It enables query logging on its own while the with block runs, so it works fine with DEBUG = False — verified on Django 6.1.2.

Does the count include middleware and session queries?

Yes — every query inside the with block is counted, including session or auth middleware if they hit the database. That’s why you should measure with CaptureQueriesContext in the real test context before pinning a number.

Tests run on SQLite but production runs PostgreSQL — does the count drift?

It can, around system queries like transactions or savepoints. The safest approach is running CI with the same database type as production, or pinning query counts on endpoints with minimal system-query involvement.

Does it work for DRF APIs, or only template views?

It works for anything the test client can call, e.g. with self.assertNumQueries(3): response = self.client.get("/api/orders/"). Combine it with select_related/prefetch_related in the ViewSet’s get_queryset() to pin an API’s query count.

Does assertNumQueries slow tests down much?

Not noticeably — it only counts queries, it doesn’t analyze each one’s content. The overhead is tiny compared to catching an N+1 regression early.

References