Part II · The ORM
Chapter 8: From Python to SQL
The promiseORM calls are SQL in Python clothing.
The machineryHow Q objects, expressions, lookups, Query join promotion, and SQLCompiler compile a Python expression tree into parameterized SQL.
Every Django developer eventually hears the shorthand that ORM calls are just SQL in Python clothing: "filter" is "WHERE", "select_related" is "JOIN", "annotate" is "SELECT ... AS", and "order_by" is "ORDER BY".
That shorthand hides the single most important architectural fact about django/: Django is not gluing SQL fragments together as you chain methods. It is building a mutable relational algebra tree — Q, WhereNode, BaseExpression, Lookup, and Query — and only lowering that tree into SQL strings and a separate parameter tuple at the very end inside SQLCompiler.
That two-phase compiler design explains the sharpest behaviors you will ever hit in production. It explains why "id__in=[]" executes zero database queries; why "published_at__year__gte=2026" rewrites itself into an index-friendly range bound; why splitting two many-to-many predicates across two chained QuerySet.filter calls creates a second "JOIN" alias and returns completely different rows; why two unrelated Count annotations silently multiply each other’s totals; and why, on a fast indexed query, 76% to 90% of wall-clock latency is Python compilation rather than SQLite execution.
Six stages in Python, and what compilation actually costs
ch08-bench, comparing identical "values_list('id', flat=True)" queries across Python compilation (Query assembly plus SQLCompiler.as_sql ), raw SQLite cursor execution on the precompiled SQL, and full end-to-end execution. On a small in-memory table, building and compiling a correlated Exists takes 524.9 us in Python while SQLite executes it in 19.0 us — 89.7% of the entire request is the ORM compiler.Walking the compiler from top to bottom
Every query against "desk/"'s newsroom schema passes through the same six boundaries:
First, boolean trees enter as Q objects built on Node, and Query.add_q lowers them into a WhereNode tree capable of emulating "XOR", partitioning "WHERE" from "HAVING" and "QUALIFY", and folding empty predicates via EmptyResultSet and FullResultSet. Second, every value-producing node — F, Value, CombinedExpression, Case, and When — shares the BaseExpression contract, resolving symbolic field names into table-qualified Col nodes bound to concrete aliases. Third, double-underscore paths like "published_at__year__gte" are split into chains of Transform nodes terminating in a Lookup dispatched through RegisterLookupMixin.
Beneath the predicates sits Query itself: an "alias_map" of BaseTable and Join entries governed by reference counts ("alias_refcount"), join trimming (Query.trim_joins), JoinPromoter, and Query. When rows are finally requested, SQLCompiler walks the finished Query, dispatches vendor-specific "as_<vendor>" hooks through SQLCompiler, keeps every user value inside the separate "params" tuple for parameter binding, and runs BaseDatabaseOperations over every raw row returning from the cursor. Finally, aggregates, Subquery, OuterRef, and Window bend the compiler’s clause structure — wrapping queries in derived tables and guarding against Cartesian join fan-out.
We start at the top of the tree — how Q combines boolean predicates and lowers them into WhereNode — in Q objects and the WhereNode tree.