Django 6.1.3

8.1 From Python to SQL

Q objects and the WhereNode tree

How do Q expressions combine with &, |, ^, and ~, and how does Query.build_filter lower them into a WhereNode tree?

When you write "Story.objects.filter((Q(desk__slug='metro') | Q(priority=1)) & ~Q(status='draft'))", Django does not emit a single character of SQL while evaluating the Python expression inside "filter(...)". Instead, it constructs an immutable-feeling tree of Q nodes whose leaves are plain (lookup_string, value) pairs, and only later lowers that tree inside Query.add_q into a WhereNode whose leaves are resolved Lookup instances bound to real table aliases.

Node: the tree algebra shared by Q and WhereNode

Both Q and WhereNode inherit from the same compact 126-line base class, Node. Every Node holds exactly three attributes: "children" (a list of leaf values or child Node instances), "connector" (a string such as "AND", "OR", or "XOR"), and "negated" (a boolean).

The key trick in Node.add is automatic flattening: if you add a non-negated child whose connector matches the parent’s connector — or a non-negated single-child node — Node.add squashes its children directly into the parent’s "children" list instead of nesting redundant brackets. Only when connectors differ (such as adding an "OR" subtree under "AND") or when a child is negated does Node.add preserve the child as its own nested node.

Q subclasses Node and overrides Python’s bitwise operators (__and__, __or__, __xor__, and __invert__, Q._combine). Combining two Q objects allocates a new Q container via Q.create and calls Node.add twice — leaving the original Q objects untouched so you can safely reuse a base filter across multiple queries. Calling "~q" clones the node via copy.copy and flips "negated" via Node.negate.

Watch how Q squashes flat conjunctions, preserves mixed "OR" / "NOT" branches, and lowers into WhereNode on "desk/"'s "Story" model:

Recorded on Django 6.1.3 ch08-sql script
1. Q trees, WhereNode, XOR lowering, and EmptyResultSet
  squashed_and = <Q: (AND: ('priority', 1), ('status', Story.Status.PUBLISHED))> children=2
  compound_q = <Q: (AND: (OR: ('desk__slug', 'metro'), ('priority', 1)), (NOT (AND: ('status', Story.Status.DRAFT))))>
  where_tree = <WhereNode: (AND: (OR: Exact(Col(newsroom_desk, newsroom.Desk.slug), 'metro'), IntegerFieldExact(Col(newsroom_story, newsroom.Story.priority), 1)), (NOT (AND: Exact(Col(newsroom_story, newsroom.Story.status), Story.Status.DRAFT))))>
  compound_sql = SELECT "newsroom_story"."id", "newsroom_story"."headline", "newsroom_story"."slug", "newsroom_story"."body", "newsroom_story"."priority", "newsroom_story"."status", "newsroom_story"."published_at", "newsroom_story"."desk_id", "newsroom_story"."reporter_id", "newsroom_story"."edition_id" FROM "newsroom_story" INNER JOIN "newsroom_desk" ON ("newsroom_story"."desk_id" = "newsroom_desk"."id") WHERE (("newsroom_desk"."slug" = %s OR "newsroom_story"."priority" = %s) AND NOT ("newsroom_story"."status" = %s)) ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
  compound_params = ('metro', 1, Story.Status.DRAFT)
  compound_slugs = ['bridge-bond-passes', 'city-budget-hearing', 'night-bus-schedule', 'water-main-repair']

Compare "compound_q" and "where_tree" line for line. The structure — root "AND", left "OR", right "NOT (AND: ...)" — survived intact, but every symbolic string leaf has been replaced by a concrete expression bound to a table alias: ('desk__slug', 'metro') became Exact(Col(newsroom_desk, newsroom.Desk.slug), 'metro') (and triggered an "INNER JOIN" onto "newsroom_desk"), while ('priority', 1) became IntegerFieldExact(Col(newsroom_story, newsroom.Story.priority), 1).

How Query.add_q and Query._add_q lower the tree

Lowering happens inside Query.add_q, which delegates recursively to Query._add_q. Walking _add_q reveals why every QuerySet.filter call is really just syntactic sugar over Q: QuerySet._filter_or_exclude_inplace wraps your positional and keyword arguments into Q(*args, **kwargs) and hands that single Q to Query.add_q.

For each node in the Q tree, Query._add_q allocates a fresh WhereNode ("target_clause") with the same connector and negation, plus a JoinPromoter sized to the number of children. Each child is dispatched in one of two ways:

Once every child finishes, JoinPromoter.update_join_types upgrades joins that would otherwise drop rows under "OR" or "NOT" (we trace that machinery in Inner vs. outer joins and multi-valued filter traps), and Query.add_q attaches the completed subtree onto Query.where.

Compiling WhereNode: XOR emulation and EmptyResultSet folding

When SQLCompiler.as_sql eventually compiles Query.where, WhereNode.as_sql does two things that surprise people who assume Django maps operators one-to-one onto SQL.

First, neither SQLite nor PostgreSQL provides a native boolean "XOR" operator (BaseDatabaseFeatures.supports_logical_xor is False on both). When WhereNode.as_sql encounters connector == XOR on a backend without native support (lines 130–147), it rewrites the node in flight before emitting SQL: it combines the children with "OR" (so at least one must hold) and appends a Case sum counting how many branches evaluate to 1 — requiring 1 = sum for two operands, or Mod(sum, 2) = 1 for three or more.

Second, WhereNode.as_sql uses Python exceptions — EmptyResultSet and FullResultSet — as compile-time algebraic identities. When you write "Story.objects.filter(id__in=[])", In.as_sql raises EmptyResultSet because no row can ever belong to the empty set. Under "AND", one EmptyResultSet child makes the entire conjunction impossible, so WhereNode.as_sql propagates EmptyResultSet straight up to SQLCompiler.execute_sql, which returns an empty iterator without opening a cursor or sending a single SQL query. Under negation ("exclude(id__in=[])"), WhereNode.as_sql flips EmptyResultSet into FullResultSet (a tautology), which SQLCompiler.as_sql drops completely so the query runs with no "WHERE" clause at all.

Watch both "XOR" lowering and EmptyResultSet / FullResultSet folding execute live on "desk/":

Recorded on Django 6.1.3 ch08-sql script
  sqlite_supports_logical_xor = False
  xor_sql = SELECT "newsroom_story"."id", "newsroom_story"."headline", "newsroom_story"."slug", "newsroom_story"."body", "newsroom_story"."priority", "newsroom_story"."status", "newsroom_story"."published_at", "newsroom_story"."desk_id", "newsroom_story"."reporter_id", "newsroom_story"."edition_id" FROM "newsroom_story" INNER JOIN "newsroom_desk" ON ("newsroom_story"."desk_id" = "newsroom_desk"."id") WHERE (("newsroom_desk"."slug" = %s OR "newsroom_story"."priority" = %s) AND %s = (CASE WHEN "newsroom_desk"."slug" = %s THEN %s ELSE %s END + CASE WHEN "newsroom_story"."priority" = %s THEN %s ELSE %s END)) ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
  xor_params = ('metro', 1, 1, 'metro', 1, 0, 1, 1, 0)
  xor_slugs = ['city-budget-hearing', 'water-main-repair']
  id__in=[] -> as_sql_raised=EmptyResultSet executed_queries=0 rows=0
  exclude(id__in=[]) -> has_WHERE=False params=() count=6

Look closely at "xor_params" (9 parameters for a two-branch "XOR"!): each predicate appears twice in SQL — once in the "OR" filter and once inside its "CASE WHEN ... THEN 1 ELSE 0 END" arm — which matters if either branch contains an expensive subquery or function call. And notice "id__in=[]": executed_queries=0, proving that Django short-circuits provably empty filters in Python before the database driver ever wakes up (the exact same mechanism powers Query.set_empty, Query.set_empty, which inserts a NothingNode, NothingNode, for "QuerySet.none()").

One more subtle duty lives on WhereNode: WhereNode.split_having_qualify. Because Query.where holds every predicate attached via QuerySet.filter — whether it tests a plain column, an aggregated Count, or a Window rank — the compiler splits Query.where just before SQL generation into three distinct trees: "WHERE" (row-level predicates), "HAVING" (branches where "contains_aggregate" is True), and "QUALIFY" (branches where "contains_over_clause" is True). We will watch "qualify" rewrite an entire "SELECT" statement into nested derived tables in Aggregates, annotations, subqueries, and windows.

First, though, what actually sits inside those WhereNode leaves and "SELECT" projections? Every column, literal, arithmetic operator, SQL function, and conditional branch shares a single expression protocol — next in Expressions, F, Value, and resolve_expression.