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

# 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

```text figure=join-vs-prefetch
select_related() (SQL JOIN) vs. prefetch_related() (Python stitching) on Django 6.1.3

1. select_related('desk', 'reporter') -> 1 SQL query, 19-column tuple sliced by RelatedPopulator:
   Story[0:10] -> Story.from_db()  |  Desk[10:14] -> RelatedPopulator #1  |  Reporter[14:19] -> RelatedPopulator #2
   local_setter writes story._state.fields_cache['desk'] & ['reporter'] -> 0 extra queries

2. prefetch_related('corrections', 'beats') -> 3 separate queries stitched in Python:
   Q1: SELECT ... FROM newsroom_story
   Q2: SELECT ... FROM newsroom_correction WHERE story_id IN (1..6)
   Q3: SELECT (story_id) AS _prefetch_related_val_story_id, beat.* FROM newsroom_beat INNER JOIN newsroom_storybeat ...
   Result stored in story._prefetched_objects_cache -> .all() hits cache (0 SQL), .filter() clones & drops cache (+1 SQL)
```

*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.*

## What `QuerySet.select_related` records — and a Django `6.1` deprecation

Open **`select_related`** (`django/db/models/query.py:QuerySet.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` (`django/db/models/sql/query.py: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`:
- A non-nullable `ForeignKey` (`"Story.desk"`, `"Story.reporter"`) compiles to an **`INNER JOIN`**.
- A nullable `ForeignKey` or `OneToOneField` (`"Reporter.user"`, `null=True`) compiles to a **`LEFT OUTER JOIN`** so rows with `user_id IS NULL` are not dropped from the result set!
- All joined tables' concrete columns are appended right after the root model's columns in the `"SELECT"` clause, and `SQLCompiler.klass_info` (`django/db/models/sql/compiler.py:SQLCompiler`) records the exact column slice `[start, ..., end]` for every model in the join tree.

## How `RelatedPopulator` unpacks one wide tuple into three models

Now open **`RelatedPopulator`** (`django/db/models/query.py: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` (`django/db/models/fetch_modes.py:FetchMode`) 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:

```text recording=ch07-querysets
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, and `RelatedPopulator` instantiates **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 beating `select_related("desk")` in both network bytes and Python CPU!
- **Wide joins plus `select_related()` without `only()`/`defer()` drag giant `TextField` blobs across every row.** Pair `select_related("desk", "reporter")` with `QuerySet.only` (`only("headline", "desk__name", "reporter__name")`) whenever you only need summary columns.
- **Multi-valued relations cannot use `select_related`.** Passing `"corrections"` or `"beats"` to `select_related()` raises `FieldError` because 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](prefetch-related.md).
