Django 6.1.3

7.5 QuerySets and laziness

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.

Open prefetch_related_objects and prefetch_one_level. Right after QuerySet._fetch_all populates _result_cache, it invokes prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups):

  1. Normalize lookups into Prefetch objects: Every plain string like "corrections" or "beats" is wrapped in Prefetch and pushed onto a work stack ("all_lookups").
  2. Prepare _prefetched_objects_cache on every instance (lines 2693–2710): Initializes _prefetched_objects_cache = {} on each root model instance.
  3. Locate the descriptor’s prefetcher (get_prefetcher, lines 2809–2871):
    • For single-valued relations (ForwardManyToOneDescriptor, ReverseOneToOneDescriptor), the descriptor itself implements get_prefetch_querysets.
    • For reverse FKs (ReverseManyToOneDescriptor) and M2M (ManyToManyDescriptor), the related manager implements get_prefetch_querysets.
  4. Run ONE batched query and group in a Python dict (prefetch_one_level, lines 2898–2981):
    • Calls get_prefetch_querysets on 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 a QuerySet from the related manager, stuffs the matched list directly into qs._result_cache = vals, marks qs._prefetch_done = True, and saves that pre-evaluated QuerySet inside obj._prefetched_objects_cache[cache_name] (lines 2971–2980)!

Why BaseManager.all hits the cache while QuerySet.filter throws it away

Now trace what happens when your template or view reads "story.corrections" after prefetch_related("corrections"):

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:

Verify all three SQL queries, _prefetched_objects_cache keys, the QuerySet.filter cache drop, and Prefetch(to_attr=...) live on our newsroom "Story" model:

Recorded on Django 6.1.3 ch07-querysets script
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

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.