python / intermediate
Snippet
Validating Database Query Efficiency in Django Unit Tests using assertNumQueries
The assertNumQueries context manager in Django TestCase verifies that code inside the block executes an exact number of SQL queries. This helps catch N+1 query regression bugs early in automated test pipelines.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
from django.test import TestCasefrom myapp.models import Authorclass QueryEfficiencyTest(TestCase):def test_author_books_fetch_count(self):Author.objects.create(name="Jane Doe")with self.assertNumQueries(1):authors = list(Author.objects.prefetch_related('books'))for author in authors:_ = list(author.books.all())
django
Breakdown
1
with self.assertNumQueries(1):
Context manager that monitors SQL queries executed and raises an AssertionError if count != 1.
2
authors = list(Author.objects.prefetch_related('books'))
Forces evaluation of the QuerySet while prefetching related books into cache in a single query.
3
for author in authors:
Iterates over cached results without triggering additional database roundtrips.