Django 6.1.3

7.6 QuerySets and laziness

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 carries a configurable fetch mode with three built-in strategies: FETCH_ONE, FETCH_PEERS, and FETCH_RAISE (raising FieldFetchBlocked).

Measuring all four strategies across 24 newsroom stories

Figure 7.3 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:

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__, 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):

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!

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

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

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

Notice a thoughtful touch across Django 6.1’s ORM: a queryset’s _fetch_mode propagates automatically into related objects!

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

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.