---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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` (`django/db/models/query.py:QuerySet`). 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` (`django/db/models/query.py:QuerySet._fetch_all`):

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

Look closely at `QuerySet.__getitem__` (`django/db/models/query.py:QuerySet.__getitem__`):

```python
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__` (`django/db/models/query.py: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:

```text recording=ch07-querysets
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:

```python
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_cache` once and the loop reuses it with `0` extra SQL.

## Where evaluation and `_result_cache` leak

- **Calling `len(qs)` instead of `QuerySet.count` when you only need a number.** `len(qs)` downloads every column of every matching row into RAM just to count the list length, whereas `QuerySet.count` asks the database engine to return one integer via `"SELECT COUNT(*)"`.
- **Logging or inspecting `repr(qs)` in debug middleware fires SQL.** `QuerySet.__repr__` (`django/db/models/query.py:QuerySet.__repr__`) evaluates `list(self[:21])`! Printing a `QuerySet` inside a hot code path or debugger watch expression hits the database for up to 21 rows every time.
- **Pickling a `QuerySet` evaluates the entire query.** Notice `QuerySet.__getstate__` (`django/db/models/query.py:QuerySet.__getstate__`): caching a `QuerySet` directly in Redis/Memcached calls `QuerySet._fetch_all` and pickles every model object (not just the SQL query!). If you only want to serialize the query definition without running it, pickle `QuerySet.query` instead.
- **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_cache` as `None`. Calling `qs[0]` in a loop (`qs[0]`, `qs[1]`, `qs[2]`) runs **N separate `"OFFSET"`/`"LIMIT 1"` queries**!

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](iterables.md).
