---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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`** (`django/db/models/query.py:QuerySet.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` (`django/db/models/query.py:prefetch_related_objects`) and `prefetch_one_level` (`django/db/models/query.py: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`** (`django/db/models/query.py: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")`:

- **`"story.corrections.all()"`:** Remember Section 7.1! `BaseManager.all` returns the related manager's `get_queryset()` **without cloning**. That `get_queryset()` finds `"corrections"` inside the instance's `_prefetched_objects_cache` and returns the pre-evaluated `QuerySet` — **`0` SQL queries**!
- **`"story.corrections.filter(note__contains='Updated')"`:** Calls `QuerySet.filter` → `QuerySet._chain` → `QuerySet._clone`, which **resets `_result_cache = None`**! Even though every single correction was already in RAM inside `_prefetched_objects_cache`, chaining `QuerySet.filter` silently drops the cache and hits SQL again (`+1` query 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`** (`django/db/models/query.py:Prefetch`) object directly into `prefetch_related`:

- `queryset=Correction.objects.filter(...).order_by("id")` applies your filter **inside the single batched prefetch query** (`"Q2"`).
- Adding `to_attr="ordered_corrections"` hits line 2969 (`setattr(obj, to_attr, vals)`): instead of hiding a `QuerySet` inside `_prefetched_objects_cache`, Django attaches a plain Python **`list`** directly onto `"story.ordered_corrections"` — making it impossible for downstream code to accidentally call `QuerySet.filter` and 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:

```text recording=ch07-querysets
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`, or `QuerySet.order_by` on a prefetched manager after the fact drops the cache.** Note a subtle bonus: `"story.corrections.count()"` calls `QuerySet.count` directly on the cached queryset (`0` SQL!), whereas `"story.corrections.filter(...).count()"` clones and runs SQL! When you need filtered counts across a list, annotate `Count("corrections", filter=Q(...))` in SQL or use `Prefetch(..., to_attr=...)`.
- **Sliced `Prefetch` querysets require window functions.** Look back at `_filter_prefetch_queryset` (`django/db/models/fields/related_descriptors.py:_filter_prefetch_queryset`): Django `6.1` supports `Prefetch("corrections", queryset=Correction.objects.order_by("-issued_at")[:3])` by rewriting the slice into a SQL `"ROW_NUMBER() OVER (PARTITION BY story_id ...)"` window function!
- **Calling `prefetch_related("corrections")` on a queryset whose `to_attr` collides with an existing field raises `ValueError`** (lines 2933–2944), and mutating a related table afterward leaves `_prefetched_objects_cache` stale until `Model.refresh_from_db` clears it.

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](fetch-modes.md).
