Iterables, values, and streaming with iterator
How do ModelIterable, ValuesIterable, and ValuesListIterable reshape identical cursor rows, and what does QuerySet 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 rows, or flat scalars is a single swappable attribute on QuerySet: _iterable_class.
Four iterables over the exact same cursor stream
Open django/ lines 121–340. All four concrete iterables subclass BaseIterable and pull rows from SQLCompiler:
ModelIterable(ModelIterable, lines 121–200 — default forall(),filter(),only(),defer()): CallsModel.from_dbon every row slice, appendsweakref.refpeers whenFETCH_PEERSis active, runs everyRelatedPopulatorforselect_related, attaches annotations viasetattr, and patches_known_related_objects.ValuesIterable(ValuesIterable— installed byQuerySet.values): SkipsModel.from_dbandModelStatecompletely! Builds onedictper row ({names[i]: row[i] for i in indexes}).ValuesListIterable(ValuesListIterable— installed byQuerySet): Returns.values_list SQLCompilerwith.results_iter tuple_expected=Truedirectly — zero extra Python wrapper loop! (Passingnamed=Trueswaps inNamedValuesListIterable, lines 304–325, wrapping each tuple viatuple.).__new__(tuple_class, row) FlatValuesListIterable(FlatValuesListIterable, lines 327–340 — installed byvalues_list("slug", flat=True)): Simply yieldsrow[0]from each single-column tuple.
Verify the iterable swap live on our newsroom "Story" model:
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):
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"):
ModelIterablewithonly(...)takes3.244 msand207.2 KBbecause every row allocates a model instance,__dict__,ModelState, and firespre_init/post_init.ValuesIterable(values(...)) drops to0.759 ms(4.3× faster!) and150.7 KB.ValuesListIterable(values_list(...)) drops to0.655 msand72.9 KB.FlatValuesListIterable(values_list("slug", flat=True)) hits0.510 msand40.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 buffers all 500,000 model instances in RAM at once.
Open QuerySet:
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 trades away (and gains) compared to ordinary iteration:
- 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 sameQuerySeta second time hits the database all over again. - Server-side cursors (
chunked_fetch=True): On PostgreSQL (and Oracle), passingchunked_fetch=Truetells Django to open a named server-side cursor and fetchchunk_sizerows at a time (2000by default) instead of lettingpsycopgbuffer the entire result set in C memory before Python sees row 1! (On SQLite,sqlite3already streams rows incrementally; on PostgreSQL behind transaction-pooled PgBouncer, named server-side cursors break across transactions unlessDISABLE_SERVER_SIDE_CURSORS = Trueis set inDATABASES!) - Chunked
prefetch_related(chunk_sizemandatory): Earlier Django versions silently ignoredprefetch_related()when combined withQuerySet. Django now raises.iterator ValueErrorif you omit"chunk_size"afterprefetch_related()(see line 22 ofch07-querysetsabove), and when you passiterator(chunk_size=500), lines 595–597 slice batches of 500 viaitertools.isliceand callprefetch_related_objectson each batch!
Where iterables and iterator() leak
- Using
values()/values_list()forfeits model methods, descriptors, andsave(). Reach forvalues_listin exports, aggregations, ID lookups, and JSON APIs where you only need raw column values; keepModelIterable(paired withonly()/defer()) when you genuinely need model behavior or writes. - Calling
iterator()inside aforloop on a small queryset that is iterated twice increases SQL count. Becauseiterator()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 turnsiterator()into client-side buffering. IfDISABLE_SERVER_SIDE_CURSORS = True,psycopgbuffers all rows from Postgres into C RAM even when you calliterator(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()crossessync_to_asynconce per chunk. Look atBaseIterable: calling._async_generator async for row in qspulls chunks of 500 across the sync-to-async thread bridge (Chapter 3) rather than crossing once per row..aiterator(chunk_size=500):
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.