Django 6.1.3

7.4 QuerySets and laziness

Eager joins with select_related

How does QuerySet.select_related turn foreign-key traversal into a single SQL JOIN, and how does ModelIterable split one wide result row into multiple model instances?

When a list view renders six newsroom stories alongside each story’s desk and reporter, accessing "story.desk.name" and "story.reporter.name" on a plain "Story.objects.all()" fires 13 SQL queries (1 for the stories + 6 for desks + 6 for reporters). Adding QuerySet.select_related (select_related("desk", "reporter")) collapses all 13 queries into one SQL statement — because SQL joins single-valued relationships (ForeignKey and OneToOneField, including reverse one-to-one) horizontally onto each row without duplicating the parent row.

Wide rows vs. Python stitching

Figure 7.2 Every column span (Story[0:10], Desk[10:14], Reporter[14:19]) and query count is parsed directly from ch07-querysets. Compare the two architectures: select_related widens each SQL row with "JOIN"s and slices columns into "_state.fields_cache", whereas prefetch_related runs separate "IN (...)" queries to avoid Cartesian row multiplication on multi-valued relations.

Open select_related:

  1. It rejects calls after QuerySet.values or QuerySet.values_list (TypeError) because ValuesIterable does not instantiate model objects or populate "_state.fields_cache".
  2. When given field paths ("desk", "reporter__user"), it clones the queryset and calls Query.add_select_related, building a nested dictionary on Query.select_related (for example {"desk": {}, "reporter": {"user": {}}}).
  3. Django 6.1 note (lines 1825–1833): Calling select_related() with no arguments (select_related = True, which automatically joins every non-null ForeignKey recursively) now emits RemovedInDjango2028Warning! Explicit field lists are now mandatory best practice so adding a new non-null ForeignKey to a model never silently turns an existing view into a 6-table join!

When SQLCompiler compiles the query (Chapter 8), it walks Query.select_related:

How RelatedPopulator unpacks one wide tuple into three models

Now open RelatedPopulator and watch ModelIterable.__iter__ (lines 149–177) unpack a 19-column cursor row from "Story.objects.select_related('desk', 'reporter')":

  1. Before iterating rows, get_related_populators(klass_info, select, db, fetch_mode) builds one RelatedPopulator per joined relation (recursively for chains like "reporter__user"), pre-computing cols_start, cols_end, init_list, pk_idx, local_setter, and remote_setter once for the entire query!
  2. For each 19-column tuple returned by the cursor:
    • ModelIterable slices row[0:10] and hydrates the "Story" via Model.from_db.
    • RelatedPopulator #1 slices row[10:14], checks obj_data[self.pk_idx] is None (if True from a LEFT OUTER JOIN miss, sets obj = None without calling from_db!), otherwise calls Model.from_db for "Desk".
    • RelatedPopulator #2 slices row[14:19] and calls Model.from_db for "Reporter".
    • Each populator calls RelatedPopulator.local_setter (storing "Desk" and "Reporter" straight into "story._state.fields_cache") and, for OneToOneField, RelatedPopulator.remote_setter so walking back across the 1:1 link also costs 0 queries!
    • Notice lines 3080–3082 on Django 6.1: if FetchMode.track_peers is True, each RelatedPopulator maintains its own RelatedPopulator.peers list of weakrefs so that later accessing "reporter.user" on one joined "Reporter" batches all joined "Reporter" instances together!

Verify the exact join count, 19-column split, and 1-query iteration live on our newsroom app:

Recorded on Django 6.1.3 ch07-querysets script
select_related() SQL JOIN and RelatedPopulator column slicing
  select_related('desk', 'reporter') JOIN count=2 total_cols=19
  column spans: Story[0:10] + Desk[10:14], Reporter[14:19]
  iterate 6 stories reading .desk.name + .reporter.name -> queries=1 sample=('Metro', 'Ada')

For reverse foreign keys, many-to-many bridges, and low-cardinality wide parents, Django switches strategies from SQL joins to Python hash-map stitching — which we open next in Second-query batching with prefetch_related.