Second-query batching with prefetch_related
How does prefetch_related eliminate N+1 queries on reverse foreign keys and many-to-many relations in Python, and why does chaining QuerySet.filter on a prefetched manager throw the cache away?
If a story has 3 corrections and 4 beats, joining both tables onto "newsroom_story" in one SQL query produces $3 \times 4 = 12$ duplicate rows for a single story! That Cartesian blowup is why prefetch_related refuses to join multi-valued relations into the root query. Instead, it executes one extra batched query per relation and joins the results in Python dictionaries.
Inside prefetch_related_objects and prefetch_one_level
Open prefetch_related_objects and prefetch_one_level. Right after QuerySet populates _result_cache, it invokes prefetch_related_objects(self:
- Normalize lookups into
Prefetchobjects: Every plain string like"corrections"or"beats"is wrapped inPrefetchand pushed onto a work stack ("all_lookups"). - Prepare
_prefetched_objects_cacheon every instance (lines 2693–2710): Initializes_prefetched_objects_cache= {}on each root model instance. - Locate the descriptor’s prefetcher (
get_prefetcher, lines 2809–2871):- For single-valued relations (
ForwardManyToOneDescriptor,ReverseOneToOneDescriptor), the descriptor itself implementsget_prefetch_querysets. - For reverse FKs (
ReverseManyToOneDescriptor) and M2M (ManyToManyDescriptor), the related manager implementsget_prefetch_querysets.
- For single-valued relations (
- Run ONE batched query and group in a Python dict (
prefetch_one_level, lines 2898–2981):- Calls
get_prefetch_querysetson the prefetcher to obtain a 6-tuple(rel_qs, rel_obj_attr, instance_attr, single, cache_name, is_descriptor). - Evaluates
all_related_objects = list(rel_qs)— 1 SQL query (WHERE "story_id" IN (1, 2, ...)for reverse FKs; for M2M"beats", joins"newsroom_storybeat"onto"newsroom_beat"and projects("newsroom_storybeat"."story_id") AS "_prefetch_related_val_story_id"so Python knows which"Story"each"Beat"belongs to!). - Buckets every related row in a plain dict
rel_obj_cache[rel_attr_val].append(rel_obj)in $O(M)$ time. - For every root
obj, builds aQuerySetfrom the related manager, stuffs the matched list directly intoqs, marks._result_cache = vals qs, and saves that pre-evaluated._prefetch_done = True QuerySetinsideobj(lines 2971–2980)!._prefetched_objects_cache[cache_name]
- Calls
Why BaseManager.all hits the cache while QuerySet.filter throws it away
Now trace what happens when your template or view reads "story after prefetch_related("corrections"):
"story: Remember Section 7.1!.corrections .all()" BaseManager.allreturns the related manager’sget_queryset()without cloning. Thatget_queryset()finds"corrections"inside the instance’s_prefetched_objects_cacheand returns the pre-evaluatedQuerySet—0SQL queries!"story: Calls.corrections .filter(note__contains='Updated')" QuerySet.filter→QuerySet._chain→QuerySet._clone, which resets_result_cache = None! Even though every single correction was already in RAM inside_prefetched_objects_cache, chainingQuerySet.filtersilently drops the cache and hits SQL again (+1query per story — bringing the N+1 bug right back!).
Customizing prefetches with Prefetch(..., queryset=..., to_attr=...)
Whenever you need a filtered, ordered, or annotated prefetched relation without breaking the cache, pass a Prefetch object directly into prefetch_related:
queryset=Correctionapplies your filter inside the single batched prefetch query (.objects .filter(...).order_by("id") "Q2").- Adding
to_attr="ordered_corrections"hits line 2969 (setattr(obj, to_attr, vals)): instead of hiding aQuerySetinside_prefetched_objects_cache, Django attaches a plain Pythonlistdirectly onto"story— making it impossible for downstream code to accidentally call.ordered_corrections" QuerySet.filterand trigger hidden SQL!
Verify all three SQL queries, _prefetched_objects_cache keys, the QuerySet.filter cache drop, and Prefetch(to_attr=...) live on our newsroom "Story" model:
prefetch_related(), Prefetch(to_attr=...), and cache invalidation on .filter()
prefetch_related('corrections', 'beats') -> queries=3
Q1: SELECT "newsroom_story"."id", "newsroom_story"."headline", "newsroom_story"."slug", "newsroom_stor
Q2: SELECT "newsroom_correction"."id", "newsroom_correction"."story_id", "newsroom_correction"."note",
Q3: SELECT ("newsroom_storybeat"."story_id") AS "_prefetch_related_val_story_id", "newsroom_beat"."id"
story._prefetched_objects_cache keys=['beats', 'corrections']
story.corrections.all() + beats.all() -> queries=0 (served from _prefetched_objects_cache)
story.corrections.filter(...) -> queries=1 (cloning drops prefetch cache!)
Prefetch(..., to_attr='ordered_corrections') -> queries=2 attr_type=list
Where prefetch_related leaks
- Calling
QuerySet.filter,QuerySet.exclude, orQuerySeton a prefetched manager after the fact drops the cache. Note a subtle bonus:.order_by "storycalls.corrections .count()" QuerySet.countdirectly on the cached queryset (0SQL!), whereas"storyclones and runs SQL! When you need filtered counts across a list, annotate.corrections .filter(...).count()" Count("corrections", filter=Q(...))in SQL or usePrefetch(..., to_attr=...). - Sliced
Prefetchquerysets require window functions. Look back at_filter_prefetch_queryset: Django6.1supportsPrefetch("corrections", queryset=Correctionby rewriting the slice into a SQL.objects .order_by("-issued_at")[: 3]) "ROW_NUMBER() OVER (PARTITION BY story_id ...)"window function! - Calling
prefetch_related("corrections")on a queryset whoseto_attrcollides with an existing field raisesValueError(lines 2933–2944), and mutating a related table afterward leaves_prefetched_objects_cachestale untilModelclears it..refresh_from_db
Both select_related and prefetch_related require you to predict upfront in your view which relations a template or serializer will touch. Django 6.1 introduces a third mechanism that changes what happens at the moment of lazy access: Django 6.1 fetch modes.