Fixing N+1 Queries in Django with prefetch_related and Prefetch Objects
Django's prefetch_related collapses N+1 queries on reverse foreign keys and many-to-many relations into two queries. Learn when to use the basic call versus the Prefetch object with to_attr, and how to verify the fix without guessing.
17 Dec 2025, 12:49 UTC

The N+1 problem that shows up in production
You ship a feature that lists authors with their recent books. In development the page loads in 50 ms. In production it takes 3 seconds. The culprit: a template loop like {{ author.book_set.all }} inside a for author in authors block. Each iteration executes a separate SELECT * FROM book WHERE author_id = ?. With 100 authors that's 101 queries—one for the author list, then one per author. This is the classic N+1 pattern, and Django's prefetch_related is the standard tool to collapse it into two queries.
How prefetch_related differs from select_related
select_related follows single-valued relationships (foreign key, one-to-one) with a SQL JOIN. It cannot traverse reverse foreign keys or many-to-many fields because those would duplicate the parent row. prefetch_related instead runs a separate query for each relationship, fetches all related objects in bulk, and joins them in Python. For a queryset Author.objects.prefetch_related('book_set'), Django issues:
SELECT * FROM author;
SELECT * FROM book WHERE author_id IN (1,2,3,...);
The second query uses an IN clause with every author primary key from the first result set. Django then attaches each book to its author instance in memory. Subsequent access to author.book_set.all() reads from that cache instead of hitting the database again.
Customizing the prefetch with Prefetch objects
The basic prefetch_related('book_set') caches results under the default related name. Sometimes you need a filtered or ordered subset, or you want to avoid name collisions. The Prefetch object solves both. Consider a dashboard that shows each author's three most recent books:
from django.db.models import Prefetch
recent_books = Prefetch(
'book_set',
queryset=Book.objects.order_by('-published_date')[:3],
to_attr='recent_books'
)
authors = Author.objects.prefetch_related(recent_books)
In the template you now iterate author.recent_books instead of author.book_set.all. The to_attr argument stores the prefetched list on a custom attribute, so the default manager remains untouched. If you later call author.book_set.all() you'll trigger a new query—intentionally or by mistake—so pick one access pattern and stick with it.
Trade-offs: memory and filtering scope
Because prefetch_related loads the entire related set into Python, memory grows with the product of parent rows and average related objects per parent. A queryset of 10,000 authors each with 50 books materializes 500,000 Book instances. Mitigate this by:
- Paginating the parent queryset (
Author.objects.all()[:100]). - Filtering the prefetch queryset aggressively (the
[:3]slice above). - Using
only()ordefer()on the prefetch queryset to avoid loading unused fields.
Another limitation: the prefetch query runs once with an IN clause containing all parent primary keys. You cannot make the prefetch filter depend on each individual parent row (e.g., "books published after the author's join date") without a Subquery or a custom Prefetch that replicates the parent filter logic. For most dashboards and list views the static IN approach is sufficient.
Verify the fix before you deploy
Add a quick check to your development workflow. In a shell with DEBUG=True:
from django.db import connection
from myapp.models import Author
# Baseline
connection.queries.clear()
list(Author.objects.all())
print(f"Baseline queries: {len(connection.queries)}")
# With prefetch
connection.queries.clear()
list(Author.objects.prefetch_related('book_set'))
print(f"Prefetched queries: {len(connection.queries)}")
You should see the count drop from N+1 to 2. In templates, wrap the loop in a {% debug %} block temporarily or use Django Debug Toolbar's SQL panel to confirm no new queries appear during iteration. This verification takes seconds and prevents regressions when someone adds a new related accessor later.
Closing thought
prefetch_related is not a magic wand—it trades database round-trips for memory and requires discipline about which attribute you access. But for the vast majority of list-and-detail views, it turns a performance cliff into a predictable two-query pattern. Start with the basic call, reach for Prefetch when you need ordering or filtering, and always verify the query count in a staging environment that mirrors your production data volume.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.