Django 6.1.3

6.1 QuerySets and laziness

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

Recorded on Django 6.1.3 specimen-querysets script
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.

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.

When _result_cache is None, _fetch_all instantiates the queryset’s iterable class — ModelIterable by default — and consumes it whole into a Python list. 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. Once _result_cache holds that list, _fetch_all becomes a no-op.

Recorded on Django 6.1.3 specimen-querysets script
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.

Figure 6.1 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.

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:

Recorded on Django 6.1.3 specimen-querysets script
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. 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.

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

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

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

Recorded on Django 6.1.3 specimen-querysets script
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']
Recorded on Django 6.1.3 specimen-querysets script
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']
Figure 6.2 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.