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

# Laziness and the result cache

When does a `QuerySet` actually talk to the database, what does it store once the rows arrive, and why can one extra attribute read inside a loop multiply your SQL queries by the number of rows?

A `QuerySet` holds two distinct things: a mutable `Query` tree describing a SQL statement not yet sent, and a result cache (`QuerySet._result_cache`) that starts as `None` (`django/db/models/query.py:QuerySet.__init__`). Every method you call on a queryset operates on one half or the other. Understanding which half a call touches explains almost every surprise in Django's ORM.

## Chaining clones the description and sends no SQL

Calling `QuerySet.filter` or `QuerySet.order_by` never contacts the database. Before mutating anything, each chainable method calls `QuerySet._chain`, which delegates to `QuerySet._clone` to build a fresh `QuerySet` carrying a copied `Query` (`django/db/models/query.py:QuerySet._chain`, `django/db/models/query.py:QuerySet._clone`, `django/db/models/sql/query.py:Query.chain`). The original queryset stays untouched, so a base queryset held in a view can safely branch into two different filtered views without corrupting either.

Watch what Django 6.1.3 executes when our newsroom app builds a filtered, ordered queryset of Metro stories:

```text recording=specimen-querysets
top = Story.objects.filter(desk=metro).order_by('priority')
  QuerySet.filter(desk=<Desk: Metro>)
    QuerySet._clone -> new QuerySet (copied Query)
  QuerySet.order_by('priority')
    QuerySet._clone -> new QuerySet (copied Query)
  top._result_cache -> None  (0 SQL queries sent)
```

Two `QuerySet` objects were allocated along the chain — one by `filter`, one by `order_by` — and the intermediate one was discarded as soon as the statement finished. Zero SQL crossed the wire, and `_result_cache` remains `None`.

> **Why.** Cloning on every step lets managers and helper functions compose queries functionally. You can pass a queryset into a paginator, an admin filter, and a permission check without defensive copies, because no refinement ever mutates the queryset a caller still holds.

## First evaluation fills `_result_cache`

The database is untouched until code asks for rows: iterating the queryset, calling `len`, testing its truth with `bool`, slicing with a step, or pickling it. Every one of those entry points calls `QuerySet._fetch_all` (`django/db/models/query.py:QuerySet._fetch_all`).

When `_result_cache` is `None`, `_fetch_all` instantiates the queryset's iterable class — `ModelIterable` by default — and consumes it whole into a Python list (`django/db/models/query.py:ModelIterable.__iter__`). Inside that loop, `SQLCompiler.execute_sql` compiles the `Query` tree into SQL, sends one statement to the database cursor, and streams rows back to `Model.from_db` to construct model instances (`django/db/models/sql/compiler.py:SQLCompiler.execute_sql`, `django/db/models/base.py:Model.from_db`). Once `_result_cache` holds that list, `_fetch_all` becomes a no-op.

```text recording=specimen-querysets
for story in top: ..., then len(top), then bool(top)
  QuerySet._fetch_all  (cache empty -> hitting database)
    ModelIterable.__iter__
    SQLCompiler.execute_sql
      SQL SELECT "newsroom_story"."id", "newsroom_story"."headline", "newsroom_story"."desk_id", "newsroom_story"."reporter_id", "newsroom_story"."priority" FROM "newsroom_story" WHERE "newsroom_story"."desk_id" = %s ORDER BY "newsroom_story"."priority" ASC  params=(1,)
    Model.from_db(Story, values=(1, 'Bridge bond passes', 1, 1, 1), fetch_mode=FetchOne)
    Model.from_db(Story, values=(2, 'Water main fixed', 1, 2, 2), fetch_mode=FetchOne)
    Model.from_db(Story, values=(3, 'Bus route extended', 1, 1, 3), fetch_mode=FetchOne)
  headlines -> ['Bridge bond passes', 'Water main fixed', 'Bus route extended']
  QuerySet._fetch_all  (cache hit: 3 rows)
  len(top) -> 3
  QuerySet._fetch_all  (cache hit: 3 rows)
  bool(top) -> True
```

Notice the two phases in one picture: Stage 1 stays purely in Python memory allocating cloned query descriptions, while Stage 2 crosses the database wire once and turns subsequent reads into zero-SQL memory lookups.

```text figure=clone-and-eval
Stage 1 (Chaining in Python, 0 SQL):
  Story.objects.filter(desk=metro) -> QuerySet #1 (_result_cache=None)
  .order_by('priority') -> top / QuerySet #2 (_result_cache=None)

Stage 2 (First evaluation & cache reuse, 1 SQL):
  for story in top -> _fetch_all() -> ModelIterable -> SQLCompiler
  -> SQL SELECT ... FROM "newsroom_story" WHERE desk_id = %s ORDER BY priority
  -> Model.from_db() x 3 -> top._result_cache = [Story #1, #2, #3]
  -> len(top), bool(top), top.count() all hit _result_cache (0 SQL)
```

*Chaining copies the query description without touching SQLite; the first evaluation runs one `"SELECT"` and populates `QuerySet._result_cache`, turning later `len`, `bool`, and `count` calls into pure memory reads.*

> **Deeper.** Calling `list` on an unevaluated queryset triggers `_fetch_all` twice — once through `QuerySet.__len__` when CPython's `list` constructor probes the length to pre-size its buffer, and once through `QuerySet.__iter__`. Only the first call hits the database; the second immediately sees the populated `_result_cache`.

## Methods that bypass or check the cache

Not every method behaves identically before and after evaluation. Before you read the trace below, predict what happens when you call `QuerySet.count` on an unevaluated queryset *fresh* versus the already-evaluated *top*:

```text recording=specimen-querysets
fresh.count() before caching vs top.count() after caching
  SQLCompiler.execute_sql
    SQL SELECT COUNT(*) AS "__count" FROM "newsroom_story" WHERE "newsroom_story"."desk_id" = %s  params=(1,)
  fresh.count() -> 3  (sent SELECT COUNT(*))
  top.count() -> 3  (reused _result_cache: 0 SQL queries)
```

`QuerySet.count` checks whether `_result_cache` is populated first (`django/db/models/query.py:QuerySet.count`). On an unevaluated queryset it asks the database for `SELECT COUNT(*)`; on an evaluated one it returns the length of `_result_cache` without another round-trip. `QuerySet.exists` follows the same rule, whereas `QuerySet.iterator` intentionally bypasses `_result_cache` altogether so large result sets do not pile up in RAM (`django/db/models/query.py:QuerySet.exists`, `django/db/models/query.py:QuerySet.iterator`).

| Operation | Before caching (`_result_cache` is `None`) | After caching (`_result_cache` filled) | Leaves cache filled? |
| --- | --- | --- | --- |
| Iteration, `len`, `bool` | Runs full `"SELECT"` and constructs all rows | Reads `_result_cache` in memory (0 SQL) | Yes |
| `QuerySet.count` | Sends `SELECT COUNT(*)` | Returns length of `_result_cache` (0 SQL) | No change |
| `QuerySet.exists` | Sends `SELECT 1 ... LIMIT 1` | Tests truth of `_result_cache` (0 SQL) | No change |
| `QuerySet.iterator` | Streams rows in chunks straight from cursor | Ignores cache and re-queries database | No |
| `QuerySet.filter`, `QuerySet.order_by` | Clones `QuerySet` with `_result_cache = None` | Clones `QuerySet` with `_result_cache = None` | No (new clone) |

*How common queryset operations interact with `QuerySet._result_cache` before and after first evaluation.*

> **Trap.** Checking a queryset's truth with `if` before calling `QuerySet.count` or slicing the first ten rows is an expensive anti-pattern: `QuerySet.__bool__` evaluates the entire queryset into `_result_cache`, loading every matching row into memory just to test whether at least one exists. Use `QuerySet.exists` when you only need a truth test, and slice before evaluating.

## Where the list illusion breaks: N+1 queries and Django 6.1 fetch modes

Even when a queryset loads its rows in one clean `"SELECT"`, model instances only carry the columns of their own table. Each foreign key attribute on a model is a `ForwardManyToOneDescriptor` (`django/db/models/fields/related_descriptors.py:ForwardManyToOneDescriptor.__get__`). Reading a *story*'s *reporter* checks the instance's relation cache; when nothing is cached there, the descriptor builds a brand-new `QuerySet` for the missing reporter and queries the database on the spot.

Watch what happens across four newsroom stories when the loop reads each *story*'s *reporter* name — and notice that Ada wrote two of the four stories, yet Django still queries `id = 1` twice:

```text recording=specimen-querysets
N+1 (default FETCH_ONE): [s.reporter.name for s in Story.objects.order_by('id')]
  QuerySet._fetch_all  (cache empty -> hitting database)
    ModelIterable.__iter__
    SQLCompiler.execute_sql
      SQL SELECT "newsroom_story"."id", "newsroom_story"."headline", "newsroom_story"."desk_id", "newsroom_story"."reporter_id", "newsroom_story"."priority" FROM "newsroom_story" ORDER BY "newsroom_story"."id" ASC  params=()
...
    SQLCompiler.execute_sql
      SQL SELECT "newsroom_reporter"."id", "newsroom_reporter"."name", "newsroom_reporter"."desk_id" FROM "newsroom_reporter" WHERE "newsroom_reporter"."id" = %s LIMIT 21  params=(1,)
...
    SQLCompiler.execute_sql
      SQL SELECT "newsroom_reporter"."id", "newsroom_reporter"."name", "newsroom_reporter"."desk_id" FROM "newsroom_reporter" WHERE "newsroom_reporter"."id" = %s LIMIT 21  params=(1,)
...
  TRAP 5 SQL queries for 4 stories -> ['Ada', 'Bram', 'Ada', 'Cora']
```

`QuerySet.select_related` eliminates the follow-up queries at SQL compile time by adding an `INNER JOIN` to the initial `"SELECT"` and hydrating both models from the same cursor row (`django/db/models/query.py:QuerySet.select_related`):

```text recording=specimen-querysets
select_related: [s.reporter.name for s in Story.objects.select_related('reporter').order_by('id')]
  QuerySet._fetch_all  (cache empty -> hitting database)
    ModelIterable.__iter__
    SQLCompiler.execute_sql
      SQL SELECT "newsroom_story"."id", "newsroom_story"."headline", "newsroom_story"."desk_id", "newsroom_story"."reporter_id", "newsroom_story"."priority", "newsroom_reporter"."id", "newsroom_reporter"."name", "newsroom_reporter"."desk_id" FROM "newsroom_story" INNER JOIN "newsroom_reporter" ON ("newsroom_story"."reporter_id" = "newsroom_reporter"."id") ORDER BY "newsroom_story"."id" ASC  params=()
...
  1 SQL query for 4 stories -> ['Ada', 'Bram', 'Ada', 'Cora']
```

> **New in 6.1.** Django 6.1 added `QuerySet.fetch_mode` with three policies: `FETCH_ONE` (the historic per-instance default), `FETCH_PEERS`, and `FETCH_RAISE` (`django/db/models/fetch_modes.py:FetchPeers`, `django/db/models/fetch_modes.py:FetchRaise`). Under `FETCH_PEERS`, every instance remembers weak references to the peers returned beside it; the first time code reads an unfetched relation on any one instance, `FetchPeers.fetch` issues a single batched `IN (...)` query for every live peer, collapsing 5 queries into 2 without rewriting the view.

```text recording=specimen-querysets
Django 6.1 FETCH_PEERS: [s.reporter.name for s in Story.objects.fetch_mode(models.FETCH_PEERS).order_by('id')]
  QuerySet._fetch_all  (cache empty -> hitting database)
    ModelIterable.__iter__
    SQLCompiler.execute_sql
      SQL SELECT "newsroom_story"."id", "newsroom_story"."headline", "newsroom_story"."desk_id", "newsroom_story"."reporter_id", "newsroom_story"."priority" FROM "newsroom_story" ORDER BY "newsroom_story"."id" ASC  params=()
    Model.from_db(Story, values=(1, 'Bridge bond passes', 1, 1, 1), fetch_mode=FetchPeers)
...
    SQLCompiler.execute_sql
      SQL SELECT "newsroom_reporter"."id", "newsroom_reporter"."name", "newsroom_reporter"."desk_id" FROM "newsroom_reporter" WHERE ("newsroom_reporter"."id") IN ((%s), (%s), (%s))  params=(1, 2, 3)
  2 SQL queries for 4 stories -> ['Ada', 'Bram', 'Ada', 'Cora']
```

```text figure=n-plus-one
Measured SQL round-trips reading story.reporter.name across 4 stories (recordings/specimen-querysets.txt):
  Default (FETCH_ONE):      5 SQL  (1 story SELECT + 4 per-row reporter SELECTs: id=1, 2, 1 again, 3)
  Django 6.1 FETCH_PEERS:   2 SQL  (1 story SELECT + 1 batched reporter WHERE id IN (1, 2, 3))
  select_related('reporter'): 1 SQL (1 INNER JOIN fetching stories and reporters together)
```

*Every SQL round-trip sent to SQLite across the same four-story loop under Django 6.1.3's default `FETCH_ONE`, peer-batched `FETCH_PEERS`, and eager `select_related`.*

> **History.** Django's ORM deliberately rejected an identity map — the global per-session object cache used by SQLAlchemy and Hibernate — from its earliest releases. That is why Ada's row (`id = 1`) was fetched twice under `FETCH_ONE`: each `QuerySet` caches only its own list, keeping memory predictable across long-lived requests at the cost of explicit `select_related`, `prefetch_related`, or `FETCH_PEERS` declarations.
