Part II · The ORM
Chapter 6: QuerySets and laziness
The promiseA queryset behaves like a list.
The machineryA 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 when the rows are finally needed.
Two halves of one object
Before evaluation, QuerySet is None. Every chainable method (QuerySet.filter, QuerySet.exclude, QuerySet) copies the queryset through QuerySet._clone, mutates the copy’s Query, and leaves the original untouched. 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. Worse, walking a foreign key inside a loop fires one new "SELECT" per row unless the query requested a join through QuerySet or enabled peer batching through Django 6.1’s QuerySet. Laziness and the result cache opens every step of that mechanism on a live Django 6.1.3 run.