---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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 (`django/db/models/query_utils.py:Q`) whose leaves are plain `(lookup_string, value)` pairs, and only later lowers that tree inside `Query.add_q` (`django/db/models/sql/query.py:Query.add_q`) into a **`WhereNode`** (`django/db/models/sql/where.py:WhereNode`) whose leaves are resolved `Lookup` (`django/db/models/lookups.py:Lookup`) instances bound to real table aliases.

## `django/utils/tree.py:Node`: the tree algebra shared by `Q` and `WhereNode`

Both `Q` and `WhereNode` inherit from the same compact 126-line base class, `Node` (`django/utils/tree.py: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` (`django/utils/tree.py: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__`, `django/db/models/query_utils.py: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` (`django/utils/tree.py:Node.negate`).

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

```text recording=ch08-sql
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` (`django/db/models/sql/query.py:Query.add_q`), which delegates recursively to `Query._add_q` (`django/db/models/sql/query.py:Query._add_q`). Walking `_add_q` reveals why every `QuerySet.filter` call is really just syntactic sugar over `Q`: `QuerySet._filter_or_exclude_inplace` (`django/db/models/query.py:QuerySet`) 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` (`django/db/models/sql/query.py:JoinPromoter`) sized to the number of children. Each child is dispatched in one of two ways:

- If the child is another `Q` (or anything with a `"resolve_expression"` method that returns a `WhereNode`), `_add_q` recurses, passing along `"branch_negated"` (whether any ancestor is negated) and `"current_negated"` (the running parity of negations).
- If the child is a `(lookup, value)` tuple, `_add_q` calls `Query.build_filter` (`django/db/models/sql/query.py:Query.build_filter`), which walks the relation path, creates or reuses joins, instantiates the target `Lookup`, and returns a `(WhereNode, needed_inner)` pair.

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](join-promotion.md)), and `Query.add_q` attaches the completed subtree onto `Query.where`.

## Compiling `WhereNode`: `XOR` emulation and `EmptyResultSet` folding

When `SQLCompiler.as_sql` (`django/db/models/sql/compiler.py:SQLCompiler.as_sql`) eventually compiles `Query.where`, `WhereNode.as_sql` (`django/db/models/sql/where.py: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` (`django/db/models/expressions.py: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`** (`django/core/exceptions.py:EmptyResultSet`) and **`FullResultSet`** (`django/core/exceptions.py:FullResultSet`) — as compile-time algebraic identities. When you write `"Story.objects.filter(id__in=[])"`, `In.as_sql` (`django/db/models/lookups.py: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` (`django/db/models/sql/compiler.py: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/"`:

```text recording=ch08-sql
  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`, `django/db/models/sql/query.py:Query.set_empty`, which inserts a `NothingNode`, `django/db/models/sql/where.py:NothingNode`, for `"QuerySet.none()"`).

One more subtle duty lives on `WhereNode`: `WhereNode.split_having_qualify` (`django/db/models/sql/where.py: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](subqueries.md).

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](expressions.md).
