---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
part: The ORM
promise: "A queryset behaves like a list."
contents: caching
---

# QuerySets and laziness

A `QuerySet` is an unexecuted query description until something demands rows; chaining copies the description without touching the database, and the first evaluation fills an in-memory result cache that subsequent reads silently reuse.

Application code builds queries in steps — filter by desk, order by priority, slice the top three, hand the result to a template. If every step spoke to the database, most queries would fetch rows that the next step discards. Django avoids that by splitting a `QuerySet` into two phases: cheap cloning of a `Query` tree in Python, followed by a single database round-trip inside `QuerySet._fetch_all` when the rows are finally needed (`django/db/models/query.py:QuerySet`, `django/db/models/query.py:QuerySet._fetch_all`).

## Two halves of one object

Before evaluation, `QuerySet._result_cache` is `None`. Every chainable method (`QuerySet.filter`, `QuerySet.exclude`, `QuerySet.order_by`) copies the queryset through `QuerySet._clone`, mutates the copy's `Query`, and leaves the original untouched (`django/db/models/query.py:QuerySet._clone`). Once evaluated, `_result_cache` holds a plain Python list produced by the queryset's iterable class, turning every subsequent iteration, `len`, or truth test into an in-memory read.

## Where the list illusion leaks

A queryset looks like a list until it does not. Calling `QuerySet.count` before evaluation sends `SELECT COUNT(*)`, whereas calling it after evaluation returns `len` of `_result_cache` with zero SQL (`django/db/models/query.py:QuerySet.count`). Worse, walking a foreign key inside a loop fires one new `"SELECT"` per row unless the query requested a join through `QuerySet.select_related` or enabled peer batching through Django 6.1's `QuerySet.fetch_mode` (`django/db/models/query.py:QuerySet.select_related`, `django/db/models/query.py:QuerySet.fetch_mode`). [Laziness and the result cache](querysets/caching.md) opens every step of that mechanism on a live Django 6.1.3 run.
