Django 6.1.3

7.3 QuerySets and laziness

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.

Four iterables over the exact same cursor stream

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

  1. ModelIterable (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 (ValuesIterable — installed by QuerySet.values): Skips Model.from_db and ModelState completely! Builds one dict per row ({names[i]: row[i] for i in indexes}).
  3. ValuesListIterable (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 (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:

Recorded on Django 6.1.3 ch07-querysets script
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):

Recorded on Django 6.1.3 ch07-bench script
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"):

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:

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

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.