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

# Iterables, values, and streaming with iterator

How do `ModelIterable`, `ValuesIterable`, and `ValuesListIterable` reshape identical cursor rows, and what does `QuerySet.iterator` trade away to save memory?

Every database driver hands Django the exact same low-level payload: batches of raw Python tuples returned by the DB-API cursor's `"fetchmany()"` method. What turns those raw tuples into `"Story"` instances, dictionaries, tuples, `collections.namedtuple` rows, or flat scalars is a single swappable attribute on `QuerySet`: `_iterable_class` (`django/db/models/query.py:QuerySet`).

## Four iterables over the exact same cursor stream

Open `django/db/models/query.py` lines 121–340. All four concrete iterables subclass `BaseIterable` (`django/db/models/query.py:BaseIterable`) and pull rows from `SQLCompiler.results_iter`:

1. **`ModelIterable`** (`django/db/models/query.py:ModelIterable`, lines 121–200 — default for `all()`, `filter()`, `only()`, `defer()`): Calls `Model.from_db` on every row slice, appends `weakref.ref` peers when `FETCH_PEERS` is active, runs every `RelatedPopulator` for `select_related`, attaches annotations via `setattr`, and patches `_known_related_objects`.
2. **`ValuesIterable`** (`django/db/models/query.py:ValuesIterable` — installed by `QuerySet.values`): Skips `Model.from_db` and `ModelState` (`django/db/models/base.py:ModelState`) completely! Builds one `dict` per row (`{names[i]: row[i] for i in indexes}`).
3. **`ValuesListIterable`** (`django/db/models/query.py:ValuesListIterable` — installed by `QuerySet.values_list`): Returns `SQLCompiler.results_iter` with `tuple_expected=True` directly — **zero extra Python wrapper loop**! (Passing `named=True` swaps in `NamedValuesListIterable`, lines 304–325, wrapping each tuple via `tuple.__new__(tuple_class, row)`.)
4. **`FlatValuesListIterable`** (`django/db/models/query.py:FlatValuesListIterable`, lines 327–340 — installed by `values_list("slug", flat=True)`): Simply yields `row[0]` from each single-column tuple.

Verify the iterable swap live on our newsroom `"Story"` model:

```text recording=ch07-querysets
Iterables: ModelIterable, ValuesIterable, ValuesListIterable, and iterator()
  all()                            -> iterable=ModelIterable          item_type=Story
  values('id', 'slug')             -> iterable=ValuesIterable         item_type=dict
  values_list('id', 'slug')        -> iterable=ValuesListIterable     item_type=tuple
  values_list('slug', flat=True)   -> iterable=FlatValuesListIterable item_type=str
  iterator(chunk_size=3) -> yielded=6 _result_cache=None
  prefetch_related().iterator() without chunk_size -> ValueError: chunk_size must be provided when using QuerySet.iterator() after prefetch_related().
```

Now look at the real latency and peak Python allocation cost across **500 `"Story"` rows** (`ch07-bench`):

```text recording=ch07-bench
Iterable hydration across 500 Story rows (7 trials + tracemalloc peak KB)
  iterable                                        median_ms    peak_kb   relative
  ModelIterable [all()]                               5.597      492.6      1.00x
  ModelIterable [only('id','headline','slug')]        3.244      207.2      0.58x
  ValuesIterable [values('id','headline','slug')]      0.759      150.7      0.14x
  ValuesListIterable [values_list(...)]               0.655       72.9      0.12x
  FlatValuesListIterable [flat=True]                  0.510       40.9      0.09x
```

Read those numbers twice! Even fetching the **exact same three columns** (`"id"`, `"headline"`, `"slug"`):
- `ModelIterable` with `only(...)` takes **`3.244 ms`** and **`207.2 KB`** because every row allocates a model instance, `__dict__`, `ModelState`, and fires `pre_init` / `post_init`.
- `ValuesIterable` (`values(...)`) drops to **`0.759 ms`** (**4.3× faster!**) and **`150.7 KB`**.
- `ValuesListIterable` (`values_list(...)`) drops to **`0.655 ms`** and **`72.9 KB`**.
- `FlatValuesListIterable` (`values_list("slug", flat=True)`) hits **`0.510 ms`** and **`40.9 KB`** — **11× faster and 12× less peak memory** than `"Story.objects.all()"`!

## Streaming large tables with `QuerySet.iterator`

When a management command, CSV export, or backfill walks 500,000 rows, materializing `_result_cache = list(self._iterable_class(self))` buffers all 500,000 model instances in RAM at once.

Open **`QuerySet.iterator`** (`django/db/models/query.py:QuerySet.iterator`):

```python
def _iterator(self, use_chunked_fetch, chunk_size):
    iterable = self._iterable_class(
        self,
        chunked_fetch=use_chunked_fetch,
        chunk_size=chunk_size or 2000,
    )
    if not self._prefetch_related_lookups or chunk_size is None:
        yield from iterable
        return

    iterator = iter(iterable)
    while results := list(islice(iterator, chunk_size)):
        prefetch_related_objects(results, *self._prefetch_related_lookups)
        yield from results
```

Look closely at the **three** things `QuerySet.iterator` trades away (and gains) compared to ordinary iteration:

1. **No `_result_cache`:** Rows are yielded straight from the generator and immediately eligible for garbage collection once the loop body advances — keeping memory flat at $O(\text{chunk\_size})$ instead of $O(N)$. The tradeoff: iterating the same `QuerySet` a second time hits the database all over again.
2. **Server-side cursors (`chunked_fetch=True`):** On PostgreSQL (and Oracle), passing `chunked_fetch=True` tells Django to open a **named server-side cursor** and fetch `chunk_size` rows at a time (`2000` by default) instead of letting `psycopg` buffer the entire result set in C memory before Python sees row 1! (On SQLite, `sqlite3` already streams rows incrementally; on PostgreSQL behind transaction-pooled PgBouncer, named server-side cursors break across transactions unless `DISABLE_SERVER_SIDE_CURSORS = True` is set in `DATABASES`!)
3. **Chunked `prefetch_related` (`chunk_size` mandatory):** Earlier Django versions silently ignored `prefetch_related()` when combined with `QuerySet.iterator`. Django now raises **`ValueError`** if you omit `"chunk_size"` after `prefetch_related()` (see line 22 of `ch07-querysets` above), and when you pass `iterator(chunk_size=500)`, lines 595–597 slice batches of 500 via `itertools.islice` and call `prefetch_related_objects` on each batch!

## Where iterables and `iterator()` leak

- **Using `values()` / `values_list()` forfeits model methods, descriptors, and `save()`.** Reach for `values_list` in exports, aggregations, ID lookups, and JSON APIs where you only need raw column values; keep `ModelIterable` (paired with `only()` / `defer()`) when you genuinely need model behavior or writes.
- **Calling `iterator()` inside a `for` loop on a small queryset that is iterated twice *increases* SQL count.** Because `iterator()` never fills `_result_cache`, using it on a 20-row queryset referenced twice in a view runs the SQL query twice for zero memory benefit.
- **`"DISABLE_SERVER_SIDE_CURSORS"` behind PgBouncer turns `iterator()` into client-side buffering.** If `DISABLE_SERVER_SIDE_CURSORS = True`, `psycopg` buffers all rows from Postgres into C RAM even when you call `iterator(chunk_size=2000)` — for truly massive tables behind PgBouncer, paginate explicitly by primary key (`WHERE id > last_id ORDER BY id LIMIT 1000`) instead.
- **Async `aiterator()` crosses `sync_to_async` once per chunk.** Look at `BaseIterable._async_generator` (`django/db/models/query.py:BaseIterable._async_generator`): calling `async for row in qs.aiterator(chunk_size=500):` pulls chunks of 500 across the sync-to-async thread bridge (Chapter 3) rather than crossing once per row.

So far we have hydrated rows from one table at a time. The instant a view follows a foreign key across tables, you face Django's two classic eager-loading engines — starting with single-query SQL joins in [Eager joins with select_related](select-related.md).
