Django 6.1.3

7.2 QuerySets and laziness

Evaluation and _result_cache

Which operations trigger QuerySet._fetch_all, which silently reuse _result_cache, and why is if qs: before slicing a classic production trap?

Every QuerySet starts life with _result_cache set to None. The moment your code demands concrete rows — not another query description — Django crosses from Stage 1 into queryset evaluation through one five-line bottleneck: QuerySet._fetch_all:

def _fetch_all(self):
    if self._result_cache is None:
        self._result_cache = list(self._iterable_class(self))
    if self._prefetch_related_lookups and not self._prefetch_done:
        self._prefetch_related_objects()

Once _result_cache holds that Python list, the QuerySet behaves like a cached list for every subsequent read — and never touches the database again unless you clone it or call a bulk write method that resets _result_cache = None.

Which operations trigger _fetch_all vs. run a specialized SQL query

Read django/db/models/query.py lines 448–526, 682–694, and 1478–1509 to see the exact split between full evaluation, targeted SQL, and cache reuse:

Operation When _result_cache is None When _result_cache is populated
iter(qs), list(qs), len(qs), bool(qs), repr(qs) When _result_cache is None Calls _fetch_all() (loads all matching rows; repr slices [:21]) When _result_cache is populated Reuses _result_cache (0 SQL)
qs[:2] (slice without step) When _result_cache is None Clones + sets "LIMIT 2" (0 SQL, returns unevaluated QuerySet!) When _result_cache is populated Slices _result_cache[:2] (0 SQL, returns list!)
qs[:5:2] (slice with step) When _result_cache is None Clones + sets "LIMIT 5", evaluates immediately (list(qs)[::2]) When _result_cache is populated Slices _result_cache[:5:2] (0 SQL)
qs[0] (integer index) When _result_cache is None Clones + sets "LIMIT 1", evaluates immediately (QuerySet._fetch_all) When _result_cache is populated Returns _result_cache[0] (0 SQL)
QuerySet.count When _result_cache is None Runs SELECT COUNT(*) AS "__count" (does not fill _result_cache) When _result_cache is populated Returns len(_result_cache) (0 SQL)
QuerySet.exists When _result_cache is None Runs SELECT 1 AS "a" ... LIMIT 1 (does not fill _result_cache) When _result_cache is populated Returns bool(_result_cache) (0 SQL)
QuerySet.contains When _result_cache is None Runs filter(pk=obj.pk).exists() (1 lightweight SQL query) When _result_cache is populated Checks obj in _result_cache (0 SQL)

Look closely at QuerySet.__getitem__:

if self._result_cache is not None:
    return self._result_cache[k]

if isinstance(k, slice):
    qs = self._chain()
    ...
    qs.query.set_limits(start, stop)
    return list(qs)[:: k.step] if k.step else qs

qs = self._chain()
qs.query.set_limits(k, k + 1)
qs._fetch_all()
return qs._result_cache[0]

Two details leap straight off those lines:

  1. Negative indexing (qs[-1]) raises ValueError("Negative indexing is not supported.") immediately (lines 497–504), because SQL has no reverse offset without reversing the "ORDER BY" clause (QuerySet.reverse or QuerySet.last).
  2. qs[:2] returns two completely different types depending on whether the queryset was already evaluated! When _result_cache is None, qs[:2] returns a lazy QuerySet (0 SQL until iterated). Once _result_cache is populated, line 507 returns self._result_cache[:2] — a plain Python list!

The if qs: before slicing trap

Now combine QuerySet.__bool__ (QuerySet.__bool__, lines 486–488, which calls QuerySet._fetch_all and returns bool(self._result_cache)) with QuerySet.__getitem__ line 506, and watch one of the nastiest silent scaling bugs in Django production code unfold live on our newsroom app:

Recorded on Django 6.1.3 ch07-querysets script
Evaluation, _result_cache, count/exists, and the `if qs:` slicing trap
  uncached qs[:2] -> queries=0 type=StoryQuerySet result_cache_is_none=True
  uncached qs.exists() -> queries=1 result=True sql=SELECT %s AS "a" FROM "newsroom_story" LIMIT 1
  uncached qs.count()  -> queries=1 result=6 sql=SELECT COUNT(*) AS "__count" FROM "newsroom_story"
  bool(qs) [if qs:] -> queries=1 cached_rows=6 has_LIMIT=False
  after bool(qs): qs[:2] type=list len=2 queries=0 (count=6, exists=True also 0 SQL!)

Trace what happens when a template writes {% if stories %} followed by {% for story in stories|slice:":2" %} — or a view writes:

if qs:
    top_two = qs[:2]

Because if qs: calls bool(qs) → _fetch_all(), Django runs SELECT ... FROM "newsroom_story" with NO "LIMIT" (has_LIMIT=False), fetches and instantiates all rows in the table into _result_cache, and then qs[:2] simply slices the first two elements off that giant Python list! On a table with 100,000 stories, you just hydrated 100,000 model objects to display two headlines!

The opposite mistake hurts too: if you are going to iterate all 100 rows of the queryset, calling if qs.exists(): followed by for row in qs: runs two SQL queries (one "SELECT 1 ... LIMIT 1" plus the full "SELECT"), whereas if qs: followed by for row in qs: runs one SQL query because the loop reuses _result_cache! Match the check to what follows:

Where evaluation and _result_cache leak

Once QuerySet._fetch_all runs, QuerySet._iterable_class turns raw database cursor rows into Python objects. Next, we compare all four built-in iterables — and see what QuerySet.iterator trades away to avoid filling _result_cache — in Iterables, values, and streaming with iterator.