Inner vs. outer joins and multi-valued filter traps
Why do combining two lookups in one QuerySet.filter call and chaining two separate QuerySet.filter calls across a many-to-many relation generate completely different SQL and different row counts?
Every Django developer eventually hits this moment: you refactor a long QuerySet.filter into two readable chained "filter(...).filter(...)" calls — or collapse two chained calls into one — and a test suite that used to pass starts returning different rows.
On "desk/", every "Story" links to "Beat" rows through "StoryBeat" (storing "primary" and "position" on the join table). In our seeded newsroom:
"bridge-bond-passes"has two"StoryBeat"rows:"transit"(primary=True) and"budget"(primary=False)."city-budget-hearing"has two"StoryBeat"rows:"budget"(primary=True) and"housing"(primary=False).
Now ask two seemingly identical questions: find stories with "story_beats__primary=True" and "story_beats__beat__slug='budget'". Put both keyword arguments in one QuerySet.filter call and Django returns 1 story ("city-budget-hearing"). Split them across two chained QuerySet.filter calls and Django returns 2 stories ("bridge-bond-passes" and "city-budget-hearing").
Single vs. chained filters across a multi-valued relation
ch08-sql. Notice why "bridge-bond-passes" appears only on the right: it has a primary beat ("transit") on one "StoryBeat" row and a "budget" beat (primary=False) on a second "StoryBeat" row.A multi-valued relation is any reverse foreign key or many-to-many edge (PathInfo) where one row on the left table can match zero, one, or many rows on the right table. Look at the single line inside Query that creates the entire divergence:
reuse = can_reuse if join.m2m else None
alias = self.join(connection, reuse=reuse)
When "join.m2m" is False (a forward foreign key like "Story.desk"), setup_joins passes "reuse=None" — telling Query.join to reuse any existing join to "newsroom_desk". When "join.m2m" is True (such as "Story -> StoryBeat"), setup_joins restricts reuse strictly to "can_reuse".
Where does "can_reuse" come from? Inside Query.add_q, Django snapshots "existing_inner" from "alias_map" before processing the Q object, and inside Query._add_q it passes "used_aliases" as "can_reuse" for every sibling predicate within that single filter() call, adding each newly created multi-valued alias into "used_aliases" as it goes:
- Inside one
filter(story_beats__primary=True, story_beats__beat__slug='budget')call, the first keyword creates"newsroom_storybeat"and records it in"used_aliases". The second keyword runs in the same_add_qcall, finds"newsroom_storybeat"inside"can_reuse", increments its refcount to2, and tests both conditions against the same"StoryBeat"row. - Across two chained
"filter(...).filter(...)"calls,Query.chainresets"used_aliases = set()". The second call sees an empty"can_reuse"set, refuses to reuse"newsroom_storybeat", and asksQueryfor a fresh alias —.table_alias "T3"— joining"newsroom_storybeat"a second time so two different"StoryBeat"rows on the same"Story"can independently satisfy the two filters!
Inspect both live "alias_map" tables and compiled SQL statements side by side on "desk/":
5. Join promotion, multi-valued M2M trap, and split_exclude
single_filter: filter(story_beats__primary=True, story_beats__beat__slug='budget')
alias='newsroom_story' kind=BaseTable table='newsroom_story' refcount=2
alias='newsroom_storybeat' kind=Join join_type='INNER JOIN' parent='newsroom_story' table='newsroom_storybeat' nullable=True refcount=2
alias='newsroom_beat' kind=Join join_type='INNER JOIN' parent='newsroom_storybeat' table='newsroom_beat' nullable=False refcount=1
table_map = {'newsroom_story': ['newsroom_story'], 'newsroom_storybeat': ['newsroom_storybeat'], 'newsroom_beat': ['newsroom_beat']}
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_storybeat" ON ("newsroom_story"."id" = "newsroom_storybeat"."story_id") INNER JOIN "newsroom_beat" ON ("newsroom_storybeat"."beat_id" = "newsroom_beat"."id") WHERE ("newsroom_beat"."slug" = %s AND "newsroom_storybeat"."primary" = %s) ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
params = ('budget', True)
slugs = ['city-budget-hearing']
chained_filter: filter(story_beats__primary=True).filter(story_beats__beat__slug='budget')
alias='newsroom_story' kind=BaseTable table='newsroom_story' refcount=2
alias='newsroom_storybeat' kind=Join join_type='INNER JOIN' parent='newsroom_story' table='newsroom_storybeat' nullable=True refcount=1
alias='T3' kind=Join join_type='INNER JOIN' parent='newsroom_story' table='newsroom_storybeat' nullable=True refcount=1
alias='newsroom_beat' kind=Join join_type='INNER JOIN' parent='T3' table='newsroom_beat' nullable=False refcount=1
table_map = {'newsroom_story': ['newsroom_story'], 'newsroom_storybeat': ['newsroom_storybeat', 'T3'], 'newsroom_beat': ['newsroom_beat']}
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_storybeat" ON ("newsroom_story"."id" = "newsroom_storybeat"."story_id") INNER JOIN "newsroom_storybeat" "T3" ON ("newsroom_story"."id" = "T3"."story_id") INNER JOIN "newsroom_beat" ON ("T3"."beat_id" = "newsroom_beat"."id") WHERE ("newsroom_storybeat"."primary" = %s AND "newsroom_beat"."slug" = %s) ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
params = (True, 'budget')
slugs = ['bridge-bond-passes', 'city-budget-hearing']
Beware one bonus side effect on chained multi-valued filters: if a story had two primary beats and two matching beats, joining "newsroom_storybeat" twice can emit duplicate "Story" rows in the result unless you append QuerySet (or filter with Exists).
Join promotion and demotion via JoinPromoter
Every new Join starts life in Query as an "INNER JOIN" — the fastest join type for the SQL planner. Upgrading an "INNER JOIN" to a "LEFT OUTER JOIN" (so rows without a matching joined record are not silently discarded) is called join promotion, managed by JoinPromoter together with Query and Query.
JoinPromoter works like a tiny election over every Q branch. First it folds negation via De Morgan’s law ("effective_connector" flips "NOT (a AND b)" into "OR" and "NOT (a OR b)" into "AND"). Each child filter votes for the table aliases that must be non-null for that child to match. Then JoinPromoter applies two exact rules:
- Promote (
Query): Under an effective.promote_joins "OR", if an alias received fewer votes than"num_children"(votes < num_children), an"INNER JOIN"on that alias would discard valid rows that matched a different"OR"branch!promote_joinswalks"alias_map"from that alias outward through every descendant join, callingJoin.promotewherever the join is nullable ("nullable=True"on nullable foreign keys or any reverse relation). - Demote (
Query): Under an effective.demote_joins "AND"— or an"OR"where every branch voted for the alias (votes == num_children) — a row with"NULL"on that join can never pass the surrounding clause anyway, sodemote_joinssafely callsJoin.demoteto turn"LEFT OUTER JOIN"right back into"INNER JOIN"for the optimizer!
Nullable exclude() and split_exclude on multi-valued relations
Two negation subtleties finish the picture in Query. First, in SQL three-valued logic, "NOT (NULL = '2026-11-25 10: evaluates to "UNKNOWN" (falsey!) — so a naive "WHERE NOT (published_at = %s)" would silently drop every draft "Story" whose "published_at" is "NULL"! Whenever "current_negated" is True on a nullable column, build_filter (lines 1630–1647) appends "AND col IS NOT NULL" inside the "NOT (...)", turning "NULL" rows into NOT (UNKNOWN AND FALSE) -> NOT FALSE -> TRUE so drafts survive.
Second, negating a multi-valued relation ("Story) cannot simply negate a flat "JOIN" — if "bridge-bond-passes" has both "transit" and "budget", a joined row for "transit" would satisfy "beat and leak "bridge-bond-passes" right back into the excluded result! So when "branch_negated" is True, build_filter calls Query, which immediately raises MultiJoin. build_filter catches MultiJoin and delegates to Query, which trims the leading path (Query.trim_start), bumps subquery aliases to "U1" / "U2", and compiles a correlated "NOT (EXISTS(...))" subquery!
Watch JoinPromoter, nullable exclude(), and split_exclude all execute live on "desk/":
promote_inner: auth_user='INNER JOIN' names=['Ada']
promote_or: auth_user='LEFT OUTER JOIN' names=['Ada', 'Bram']
demote_and: auth_user='INNER JOIN' names=['Ada']
exclude_nullable_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" WHERE NOT ("newsroom_story"."published_at" = %s AND "newsroom_story"."published_at" IS NOT NULL) ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
exclude_nullable_params = ('2026-11-25 10:15:00',)
exclude_nullable_slugs = ['city-budget-hearing', 'night-bus-schedule', 'water-main-repair', 'zoning-board-tables-plan', 'riverfront-stadium-lease']
split_exclude_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" WHERE NOT (EXISTS(SELECT %s AS "a" FROM "newsroom_storybeat" "U1" INNER JOIN "newsroom_beat" "U2" ON ("U1"."beat_id" = "U2"."id") WHERE ("U2"."slug" = %s AND "U1"."story_id" = ("newsroom_story"."id")) LIMIT 1)) ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
split_exclude_params = (1, 'budget')
split_exclude_slugs = ['night-bus-schedule', 'water-main-repair', 'zoning-board-tables-plan', 'riverfront-stadium-lease']
Look at "zoning-board-tables-plan" sitting safely inside "exclude_nullable_slugs" despite "published_at=None", and look at "split_exclude_sql" cleanly excluding both "bridge-bond-passes" and "city-budget-hearing" via "NOT (EXISTS(... LIMIT 1))" using bumped aliases "U1" and "U2".
With "alias_map", "where", "select", and join types all finalized inside Query, we are ready for the moment Django finally writes SQL text, binds parameters, and decodes cursor rows — next in SQLCompiler.as_sql and parameter binding.