Evaluation and _result_cache
Which operations trigger QuerySet, 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:
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/ lines 448–526, 682–694, and 1478–1509 to see the exact split between full evaluation, targeted SQL, and cache reuse:
| Operation | When _result_ |
When _result_cache is populated |
|---|---|---|
iter(qs), list(qs), len(qs), bool(qs), repr(qs) |
When _result_ 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_ Clones + sets "LIMIT 2" (0 SQL, returns unevaluated QuerySet!) |
When _result_cache is populated Slices _result_ (0 SQL, returns list!) |
qs[:5:2] (slice with step) |
When _result_ Clones + sets "LIMIT 5", evaluates immediately (list(qs)[::2]) |
When _result_cache is populated Slices _result_ (0 SQL) |
qs[0] (integer index) |
When _result_ Clones + sets "LIMIT 1", evaluates immediately (Query) |
When _result_cache is populated Returns _result_cache[0] (0 SQL) |
QuerySet.count |
When _result_ Runs SELECT COUNT(*) AS "__count" (does not fill _result_cache) |
When _result_cache is populated Returns len(_result_ (0 SQL) |
QuerySet.exists |
When _result_ Runs SELECT 1 AS "a" ... LIMIT 1 (does not fill _result_cache) |
When _result_cache is populated Returns bool(_result_ (0 SQL) |
Query |
When _result_ Runs filter(pk=obj (1 lightweight SQL query) |
When _result_cache is populated Checks obj in _result_ (0 SQL) |
Look closely at QuerySet:
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:
- Negative indexing (
qs[-1]) raisesValueError("Negative indexing is not supported.")immediately (lines 497–504), because SQL has no reverse offset without reversing the"ORDER BY"clause (QuerySet.reverseorQuerySet.last). qs[:2]returns two completely different types depending on whether the queryset was already evaluated! When_result_cache is None,qs[:2]returns a lazyQuerySet(0SQL until iterated). Once_result_cacheis populated, line 507 returnsself— a plain Python._result_cache[: 2] list!
The if qs: before slicing trap
Now combine QuerySet (QuerySet, lines 486–488, which calls QuerySet and returns bool(self) with QuerySet line 506, and watch one of the nastiest silent scaling bugs in Django production code unfold live on our newsroom app:
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: — 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:
- Checking existence without loading the whole queryset (or before slicing): use
QuerySet.exists(SELECT 1 ... LIMIT 1) or slice first (top_two = list(qs[:).2]) - Checking non-emptiness right before iterating the entire queryset:
if qs:fills_result_cacheonce and the loop reuses it with0extra SQL.
Where evaluation and _result_cache leak
- Calling
len(qs)instead ofQuerySet.countwhen you only need a number.len(qs)downloads every column of every matching row into RAM just to count the list length, whereasQuerySet.countasks the database engine to return one integer via"SELECT COUNT(*)". - Logging or inspecting
repr(qs)in debug middleware fires SQL.QuerySetevaluates.__repr__ list(self[:21])! Printing aQuerySetinside a hot code path or debugger watch expression hits the database for up to 21 rows every time. - Pickling a
QuerySetevaluates the entire query. NoticeQuerySet: caching a.__getstate__ QuerySetdirectly in Redis/Memcached callsQuerySetand pickles every model object (not just the SQL query!). If you only want to serialize the query definition without running it, pickle._fetch_all QuerySet.queryinstead. - Forgetting that
qs[0]evaluates a clone, NOT the parent queryset itself. Look back at lines 522–525:qs[0]creates a clone with"LIMIT 1"and evaluates the clone, leaving the original_result_cacheasNone. Callingqs[0]in a loop (qs[0],qs[1],qs[2]) runs N separate"OFFSET"/"LIMIT 1"queries!
Once QuerySet runs, QuerySet turns raw database cursor rows into Python objects. Next, we compare all four built-in iterables — and see what QuerySet trades away to avoid filling _result_cache — in Iterables, values, and streaming with iterator.