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

# Django 6.1 fetch modes

How do Django 6.1's `FETCH_ONE`, `FETCH_PEERS`, and `FETCH_RAISE` change lazy field and relation access without rewriting views?

For twenty years, Django offered only one behavior when code touched an unjoined foreign key or deferred column: load **that single row** on demand — silently turning a 24-row loop into 73 database round-trips. Starting in **Django `6.1`**, every `QuerySet` and `ModelState` (`django/db/models/base.py:ModelState`) carries a configurable **fetch mode** (`django/db/models/fetch_modes.py:FetchMode`) with three built-in strategies: **`FETCH_ONE`**, **`FETCH_PEERS`**, and **`FETCH_RAISE`** (raising **`FieldFetchBlocked`**).

## Measuring all four strategies across 24 newsroom stories

```text figure=fetch-modes-wire
Django 6.1 fetch modes across 24 stories (.desk + .reporter + .corrections, 7 trials)

1. Total SQL queries issued & median latency:
   FETCH_ONE (default N+1)              73 SQL · 22.150 ms  (9.74x)
   FETCH_PEERS (auto-batches FKs only)  27 SQL · 10.118 ms  (4.45x)
   FETCH_PEERS + prefetch_related        4 SQL ·  2.753 ms  (1.21x)
   select_related + prefetch_related     2 SQL ·  2.275 ms  (1.00x)

2. Why FETCH_PEERS drops 73 -> 27 queries (and stops at reverse FKs):
   1. ModelIterable tracks weakref.ref(obj) peers in a shared list on every s._state.peers
   2. First .desk or .reporter miss batches ALL 24 siblings in 1 WHERE (id) IN ((%s), ...) query (48 -> 2 SQL)
   3. Reverse RelatedManagers (story.corrections.all()) are NOT peer-batched yet -> pair with prefetch_related
```

*Every SQL count and millisecond bar is parsed directly from `ch07-bench`. Look at that sharp, real boundary discovered by measuring live on Django `6.1.3`: switching a queryset to `FETCH_PEERS` immediately collapses **48** forward-FK queries down to **2** (`73 -> 27`), while pairing it with `prefetch_related("corrections")` drops the entire endpoint to `4` queries (`2.753 ms`) — almost matching hand-tuned `select_related + prefetch_related` (`2` queries, `2.275 ms`)!*

## Inside `django/db/models/fetch_modes.py` and `ModelIterable`

Open `django/db/models/fetch_modes.py` — the entire module is 61 lines of crystal-clear Python:

- **`FETCH_ONE`** (`django/db/models/fetch_modes.py:FetchOne`): Django's classic default (`track_peers = False`). Its `fetch(fetcher, instance)` simply invokes `fetch_one` on the descriptor, running one SQL query for that single object.
- **`FETCH_PEERS`** (`django/db/models/fetch_modes.py:FetchPeers`): Sets `track_peers = True`. Look at how `ModelIterable.__iter__` (`django/db/models/query.py:ModelIterable`) wires up peer tracking as rows stream off the cursor:

```python
peers = []
for row in compiler.results_iter(results):
    obj = from_db(db, init_list, row[model_fields_start:model_fields_end])
    if fetch_mode.track_peers:
        peers.append(weak_ref(obj))
        obj._state.peers = peers
```

Because `peers` stores **`weakref.ref`** handles (and `ModelState.__getstate__`, `django/db/models/base.py:ModelState.__getstate__`, strips `"peers"` before pickling), tracking peers never creates reference cycles or leaks garbage-collected instances! When your loop reads `"stories[0].desk"`, `ForwardManyToOneDescriptor.__get__` calls `FetchPeers.fetch(self, instance)`:

```python
instances = [
    peer
    for peer_weakref in instance._state.peers
    if (peer := peer_weakref()) is not None
]
if len(instances) > 1:
    fetcher.fetch_many(instances)
else:
    fetcher.fetch_one(instance)
```

For `ForwardManyToOneDescriptor`, `fetch_many` calls `prefetch_related_objects(missing_instances, self.field.name)`, issuing **one** `WHERE ("newsroom_desk"."id") IN ((%s), (%s), ...)` query (using Django `6.1`'s tuple-`"IN"` syntax for composite-PK compatibility!) and filling `_state.fields_cache["desk"]` on every sibling `"Story"` at once! For `DeferredAttribute`, `fetch_many` issues **one** `SELECT id, body WHERE id IN (...)` query and populates `"body"` on every sibling!

- **`FETCH_RAISE`** (`django/db/models/fetch_modes.py:FetchRaise`): Executes **0 SQL** and immediately raises **`FieldFetchBlocked`** (`django/core/exceptions.py:FieldFetchBlocked`): `f"Fetching of {klass}.{field_name} blocked."`.

Watch all three fetch modes — including `FETCH_PEERS` on both unjoined FKs and `QuerySet.defer` — execute live on our newsroom `"Story"` model:

```text recording=ch07-querysets
Django 6.1 fetch modes: FETCH_ONE vs FETCH_PEERS vs FETCH_RAISE
  FETCH_ONE   (6 stories -> .desk + .reporter) -> queries=13 (1 + 12 N+1 queries)
  FETCH_PEERS (6 stories -> .desk + .reporter) -> queries=3 peers_tracked=6
    peer batch SQL: SELECT "newsroom_desk"."id", "newsroom_desk"."name", "newsroom_desk"."slug", "newsroom_desk"."section_code" FROM "newsroom_desk" WHERE ("newsroom_desk"."id") IN ((%s), (%s), (%s))
  FETCH_PEERS + .defer('body') across 6 stories -> queries=2 (1 initial + 1 batch IN)
  FETCH_RAISE unjoined .desk -> queries=0 FieldFetchBlocked: Fetching of Story.desk blocked.
```

And compare the 24-story wire benchmark (`ch07-bench`):

```text recording=ch07-bench
N+1 wire comparison across 24 stories (.desk + .reporter + .corrections, 7 trials)
  strategy                                 sql_queries  median_ms   relative
  FETCH_ONE (naive N+1)                             73     22.150      9.74x
  FETCH_PEERS (auto-batches FKs only)               27     10.118      4.45x
  FETCH_PEERS + prefetch_related                     4      2.753      1.21x
  select_related + prefetch_related                  2      2.275      1.00x
```

## Propagating fetch modes across related queries

Notice a thoughtful touch across Django `6.1`'s ORM: a queryset's `_fetch_mode` **propagates automatically** into related objects!
- `RelatedPopulator` passes `fetch_mode` into `from_db` and builds its own `RelatedPopulator.peers` list for joined relations (`query.py`, lines 3063, 3080–3082).
- `ForwardManyToOneDescriptor.get_queryset` calls `QuerySet.fetch_mode` with `"instance._state.fetch_mode"` (`related_descriptors.py`, line 172).
- The reverse manager inside `create_reverse_many_to_one_manager` (`django/db/models/fields/related_descriptors.py:create_reverse_many_to_one_manager`) copies `"instance._state.fetch_mode"` onto every child queryset.

So calling `QuerySet.fetch_mode` with `FETCH_PEERS` (or `FETCH_RAISE`) once on the root queryset — or inside a custom `BaseManager.get_queryset` — automatically governs child objects loaded through that queryset too!

## Where Django `6.1` fetch modes leak

- **`FETCH_PEERS` does NOT batch reverse many-to-one (`"story.corrections.all()"`) or many-to-many (`"story.beats.all()"`) managers.** As our 24-story benchmark proved (`73 -> 27` queries, *not* `4`), `FETCH_PEERS` handles `DeferredAttribute`, `ForwardManyToOneDescriptor`, and `ReverseOneToOneDescriptor` — all single-object descriptors. Reverse collections still need `prefetch_related(...)`.
- **`FETCH_RAISE` catches missing `select_related` and `defer`, NOT missing `prefetch_related` on reverse managers.** Calling `"story.corrections.all()"` returns a `QuerySet` directly rather than calling `FetchMode.fetch`, so `FETCH_RAISE` will not block unprefetched reverse manager queries (use `assertNumQueries` in tests alongside `FETCH_RAISE` for full coverage!).
- **Peer batching works only for siblings still alive in Python memory.** Because `ModelState.peers` (`django/db/models/base.py:ModelState`) stores `weakref.ref` handles, streaming a queryset with `QuerySet.iterator()` (where only one row is alive at a time) means `len(instances) == 1` — so `FETCH_PEERS` degrades gracefully to `fetch_one` without buffering rows in RAM!

We have covered every reading and eager-loading strategy in `QuerySet`. The final section of Chapter 7 turns to writing rows in bulk without per-row `Model.save` loops: [Updates, bulk_create, and cache invalidation](bulk-writes.md).
