Eager joins with select_related
How does QuerySet 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 and "story on a plain "Story fires 13 SQL queries (1 for the stories + 6 for desks + 6 for reporters). Adding QuerySet (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
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.What QuerySet.select_related records — and a Django 6.1 deprecation
Open select_related:
- It rejects calls after
QuerySet.valuesorQuerySet(.values_list TypeError) becauseValuesIterabledoes not instantiate model objects or populate"_state..fields_cache" - When given field paths (
"desk","reporter__user"), it clones the queryset and callsQuery, building a nested dictionary on.add_select_related Query(for example.select_related {"desk": {}, "reporter": {"user": {}}}). - Django
6.1note (lines 1825–1833): Callingselect_related()with no arguments (select_related = True, which automatically joins every non-nullForeignKeyrecursively) now emitsRemovedInDjango2028Warning! Explicit field lists are now mandatory best practice so adding a new non-nullForeignKeyto a model never silently turns an existing view into a 6-table join!
When SQLCompiler compiles the query (Chapter 8), it walks Query:
- A non-nullable
ForeignKey("Story.desk","Story.reporter") compiles to anINNER JOIN. - A nullable
ForeignKeyorOneToOneField("Reporter.user",null=True) compiles to aLEFT OUTER JOINso rows withuser_id IS NULLare not dropped from the result set! - All joined tables’ concrete columns are appended right after the root model’s columns in the
"SELECT"clause, andSQLCompilerrecords the exact column slice.klass_info [start, ..., end]for every model in the join tree.
How RelatedPopulator unpacks one wide tuple into three models
Now open RelatedPopulator and watch ModelIterable (lines 149–177) unpack a 19-column cursor row from "Story:
- Before iterating rows,
get_related_populators(klass_info, select, db, fetch_mode)builds oneRelatedPopulatorper joined relation (recursively for chains like"reporter__user"), pre-computingcols_start,cols_end,init_list,pk_idx,local_setter, andremote_setteronce for the entire query! - For each 19-column tuple returned by the cursor:
ModelIterableslicesrow[0:10]and hydrates the"Story"viaModel.from_db.RelatedPopulator #1slicesrow[10:14], checksobj_data[self(if.pk_idx] is None Truefrom aLEFT OUTER JOINmiss, setsobj = Nonewithout callingfrom_db!), otherwise callsModel.from_dbfor"Desk".RelatedPopulator #2slicesrow[14:19]and callsModel.from_dbfor"Reporter".- Each populator calls
RelatedPopulator(storing.local_setter "Desk"and"Reporter"straight into"story) and, for._state .fields_cache" OneToOneField,RelatedPopulatorso walking back across the 1:1 link also costs.remote_setter 0queries! - Notice lines 3080–3082 on Django
6.1: ifFetchModeis.track_peers True, eachRelatedPopulatormaintains its ownRelatedPopulatorlist of weakrefs so that later accessing.peers "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:
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')
Where select_related backfires
- Repeated parent rows waste bandwidth and Python object allocations. Notice what happens when 500
"Story"rows all belong to only 3"Desk"rows: SQL duplicates all 4 columns of"Desk"across all 500 rows on the wire, andRelatedPopulatorinstantiates 500 separate Python"Desk"objects for those 3 desks! When a parent table has wide text/JSON columns and very low cardinality (e.g. 500 stories sharing 3 desks),prefetch_related("desk")fetches only 3"Desk"rows total in a second tiny query and shares those 3 Python instances across all 500 stories — often beatingselect_related("desk")in both network bytes and Python CPU! - Wide joins plus
select_related()withoutonly()/defer()drag giantTextFieldblobs across every row. Pairselect_related("desk", "reporter")withQuerySet.only(only("headline", "desk__name", "reporter__name")) whenever you only need summary columns. - Multi-valued relations cannot use
select_related. Passing"corrections"or"beats"toselect_related()raisesFieldErrorbecause SQL joins on 1-to-N or M2M relations multiply parent rows (Cartesian explosion).
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.