"""Chapter 7 recording: QuerySet cloning, _result_cache, iterables, select_related, prefetch_related, Django 6.1 fetch modes (FETCH_ONE / FETCH_PEERS / FETCH_RAISE), and bulk writes on `desk/` (Django 6.1.3). Run via: python recordings/run.py ch07-querysets """ from __future__ import annotations import re import sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT / "recordings")) from harness import Recorder, boot_desk def _clean_sql(sql: str) -> str: return re.sub(r"\s+", " ", sql).strip() def _sql_ops(queries: list[tuple[str, tuple]]) -> list[str]: return [s.split()[0] for s, _ in queries if not s.startswith(("SAVEPOINT", "RELEASE"))] def main() -> None: boot_desk() from django.core.exceptions import FieldFetchBlocked from django.db import transaction from django.db.models import FETCH_ONE, FETCH_PEERS, FETCH_RAISE, Prefetch from django.db.models.query import ( FlatValuesListIterable, ModelIterable, ValuesIterable, ValuesListIterable, ) from django.utils import timezone from newsroom.models import Correction, Desk, Story, StoryQuerySet rec = Recorder("ch07-querysets") # 1. Manager forwarding, _clone(), and PreventQuerySetCloning with rec.block("Managers, QuerySet._clone(), and PreventQuerySetCloning"): mgr = Story.objects rec.emit(f"type(Story.objects)={type(mgr).__name__} _queryset_class={mgr._queryset_class.__name__} built_with_as_manager={getattr(mgr, '_built_with_as_manager', False)}") with rec.capture_sql(log=False) as q_chain: qs1 = Story.objects.published() qs2 = qs1.for_desk("metro") qs3 = qs2.order_by("id") rec.emit(f"chained 3 methods -> queries={q_chain.count} distinct_qs={len({id(qs1), id(qs2), id(qs3)})} distinct_query={len({id(qs1.query), id(qs2.query), id(qs3.query)})}") rec.emit(f"clone shares _hints={qs1._hints is qs2._hints} shares _known_related_objects={qs1._known_related_objects is qs2._known_related_objects}") qs_inplace = Story.objects.all() before_id = id(qs_inplace) with qs_inplace._avoid_cloning(): qs_after = qs_inplace.filter(status=Story.Status.PUBLISHED).order_by("id") rec.emit(f"inside _avoid_cloning(): same_qs_object={id(qs_after) == before_id} cloning_restored={qs_after._cloning_enabled}") # 2. Evaluation, _result_cache, and the `if qs:` before slicing trap with rec.block("Evaluation, _result_cache, count/exists, and the `if qs:` slicing trap"): qs = Story.objects.order_by("id") with rec.capture_sql(log=False) as q_s1: sliced = qs[:2] rec.emit(f"uncached qs[:2] -> queries={q_s1.count} type={type(sliced).__name__} result_cache_is_none={qs._result_cache is None}") with rec.capture_sql(log=False) as q_ex: has_any = qs.exists() with rec.capture_sql(log=False) as q_cnt: total = qs.count() rec.emit(f"uncached qs.exists() -> queries={q_ex.count} result={has_any} sql={_clean_sql(q_ex.queries[0][0])}") rec.emit(f"uncached qs.count() -> queries={q_cnt.count} result={total} sql={_clean_sql(q_cnt.queries[0][0])}") # Trap: `if qs:` evaluates ALL rows, then `qs[:2]` slices in Python (no LIMIT!) qs_trap = Story.objects.order_by("id") with rec.capture_sql(log=False) as q_bool: truthy = bool(qs_trap) with rec.capture_sql(log=False) as q_after_bool: top2 = qs_trap[:2] c_cached = qs_trap.count() e_cached = qs_trap.exists() rec.emit(f"bool(qs) [if qs:] -> queries={q_bool.count} cached_rows={len(qs_trap._result_cache)} has_LIMIT={'LIMIT' in q_bool.queries[0][0]}") rec.emit(f"after bool(qs): qs[:2] type={type(top2).__name__} len={len(top2)} queries={q_after_bool.count} (count={c_cached}, exists={e_cached} also 0 SQL!)") # 3. Iterables and QuerySet.iterator() with rec.block("Iterables: ModelIterable, ValuesIterable, ValuesListIterable, and iterator()"): base = Story.objects.order_by("id") for label, q_obj in [ ("all()", base), ("values('id', 'slug')", base.values("id", "slug")), ("values_list('id', 'slug')", base.values_list("id", "slug")), ("values_list('slug', flat=True)", base.values_list("slug", flat=True)), ]: first_item = q_obj[0] rec.emit(f"{label:32} -> iterable={q_obj._iterable_class.__name__:22} item_type={type(first_item).__name__}") qs_it = Story.objects.order_by("id") rows_it = list(qs_it.iterator(chunk_size=3)) rec.emit(f"iterator(chunk_size=3) -> yielded={len(rows_it)} _result_cache={qs_it._result_cache}") try: _ = Story.objects.prefetch_related("corrections").iterator() except ValueError as exc: rec.emit(f"prefetch_related().iterator() without chunk_size -> ValueError: {exc}") # 4. select_related and RelatedPopulator with rec.block("select_related() SQL JOIN and RelatedPopulator column slicing"): qs_sr = Story.objects.select_related("desk", "reporter").order_by("id") compiler = qs_sr.query.get_compiler(using="default") sql_sr, _ = compiler.as_sql() compiler.pre_sql_setup() root_cols = compiler.klass_info["select_fields"] rel_spans = [ f"{rk['model'].__name__}[{rk['select_fields'][0]}:{rk['select_fields'][-1] + 1}]" for rk in compiler.klass_info["related_klass_infos"] ] rec.emit(f"select_related('desk', 'reporter') JOIN count={sql_sr.count('JOIN')} total_cols={len(compiler.select)}") rec.emit(f"column spans: Story[{root_cols[0]}:{root_cols[-1] + 1}] + {', '.join(rel_spans)}") with rec.capture_sql(log=False) as q_sr: stories_sr = list(qs_sr) names = [(s.desk.name, s.reporter.name) for s in stories_sr] rec.emit(f"iterate {len(stories_sr)} stories reading .desk.name + .reporter.name -> queries={q_sr.count} sample={names[0]!r}") # 5. prefetch_related, Prefetch, and _prefetched_objects_cache with rec.block("prefetch_related(), Prefetch(to_attr=...), and cache invalidation on .filter()"): with rec.capture_sql(log=False) as q_pf: stories_pf = list(Story.objects.prefetch_related("corrections", "beats").order_by("id")) rec.emit(f"prefetch_related('corrections', 'beats') -> queries={q_pf.count}") for idx, (s, _) in enumerate(q_pf.queries, 1): rec.emit(f" Q{idx}: {_clean_sql(s)[:98]}") s0 = stories_pf[0] rec.emit(f"story._prefetched_objects_cache keys={sorted(s0._prefetched_objects_cache)}") with rec.capture_sql(log=False) as q_pf_hit: _ = list(s0.corrections.all()) _ = list(s0.beats.all()) with rec.capture_sql(log=False) as q_pf_miss: _ = list(s0.corrections.filter(note__contains="Updated")) rec.emit(f"story.corrections.all() + beats.all() -> queries={q_pf_hit.count} (served from _prefetched_objects_cache)") rec.emit(f"story.corrections.filter(...) -> queries={q_pf_miss.count} (cloning drops prefetch cache!)") with rec.capture_sql(log=False) as q_toattr: stories_ta = list( Story.objects.prefetch_related( Prefetch("corrections", queryset=Correction.objects.order_by("id"), to_attr="ordered_corrections") ).order_by("id") ) rec.emit(f"Prefetch(..., to_attr='ordered_corrections') -> queries={q_toattr.count} attr_type={type(stories_ta[0].ordered_corrections).__name__}") # 6. Django 6.1 fetch modes: FETCH_ONE, FETCH_PEERS, FETCH_RAISE with rec.block("Django 6.1 fetch modes: FETCH_ONE vs FETCH_PEERS vs FETCH_RAISE"): with rec.capture_sql(log=False) as q_one: rows_one = list(Story.objects.fetch_mode(FETCH_ONE).order_by("id")) _ = [(s.desk.name, s.reporter.name) for s in rows_one] rec.emit(f"FETCH_ONE ({len(rows_one)} stories -> .desk + .reporter) -> queries={q_one.count} (1 + {q_one.count - 1} N+1 queries)") with rec.capture_sql(log=False) as q_peers: rows_peers = list(Story.objects.fetch_mode(FETCH_PEERS).order_by("id")) peer_count = len(rows_peers[0]._state.peers) _ = [(s.desk.name, s.reporter.name) for s in rows_peers] rec.emit(f"FETCH_PEERS ({len(rows_peers)} stories -> .desk + .reporter) -> queries={q_peers.count} peers_tracked={peer_count}") rec.emit(f" peer batch SQL: {_clean_sql(q_peers.queries[1][0])}") with rec.capture_sql(log=False) as q_def_peers: rows_dp = list(Story.objects.defer("body").fetch_mode(FETCH_PEERS).order_by("id")) _ = [len(s.body) for s in rows_dp] rec.emit(f"FETCH_PEERS + .defer('body') across {len(rows_dp)} stories -> queries={q_def_peers.count} (1 initial + 1 batch IN)") rows_raise = list(Story.objects.fetch_mode(FETCH_RAISE).order_by("id")) with rec.capture_sql(log=False) as q_raise: try: _ = rows_raise[0].desk except FieldFetchBlocked as exc: rec.emit(f"FETCH_RAISE unjoined .desk -> queries={q_raise.count} FieldFetchBlocked: {exc}") # 7. Bulk writes: update(), bulk_create(), bulk_update(), and _result_cache invalidation with rec.block("Bulk writes: update(), bulk_create(), bulk_update(), and _result_cache"): now = timezone.now() story = Story.objects.order_by("id").first() with transaction.atomic(): qs_cache = Story.objects.filter(pk=story.pk) _ = list(qs_cache) before_cache = qs_cache._result_cache is not None with rec.capture_sql(log=False) as q_upd: updated_n = qs_cache.update(priority=1) rec.emit(f"qs.update(priority=1) -> rows={updated_n} queries={q_upd.count} cache_before={before_cache} cache_after={qs_cache._result_cache}") new_corrs = [Correction(story=story, note=f"Bulk note {i}", issued_at=now) for i in range(3)] with rec.capture_sql(log=False) as q_bc: created = Correction.objects.bulk_create(new_corrs) pks_set = all(c.pk is not None for c in created) rec.emit(f"bulk_create(3) -> queries={q_bc.count} all_pks_populated={pks_set} has_RETURNING={'RETURNING' in q_bc.queries[0][0]}") for idx, c in enumerate(created): c.note = f"Edited note {idx}" with rec.capture_sql(log=False) as q_bu: bu_rows = Correction.objects.bulk_update(created, ["note"]) bu_sql = [s for s, _ in q_bu.queries if s.startswith("UPDATE")][0] rec.emit(f"bulk_update(3, ['note']) -> rows={bu_rows} has_CASE_WHEN={'CASE WHEN' in bu_sql}") rec.emit(f" bulk_update SQL: {_clean_sql(bu_sql)}") transaction.set_rollback(True) rec.write() if __name__ == "__main__": main()