Lookups, transforms, and the lookup registry
How does Django parse "published_at__year__gte" into a chain of transforms ending in a lookup, and how does RegisterLookupMixin dispatch custom operators?
Double-underscore filter strings are the most recognizable syntax in Django, and also one of the easiest to misread. In "Story, the string "published_at__year__gte" crosses two completely different registries: "published_at" is a field name resolved against Options, "year" is a Transform that wraps a Col into a new expression, and "gte" is a Lookup that turns (lhs, rhs) into a SQL boolean predicate.
Even better: when you actually run "published_at__year__gte=2026" on Django 6.1.3, the lookup registry pulls off an optimization that catches almost everyone by surprise.
Splitting a "__" path: fields, then transforms, then one lookup
When Query receives ("published_at__year__gte", 2026), it splits the string on "__" (LOOKUP_SEP) into ["published_at", "year", "gte"] and separates relation traversal from operators in two passes:
- Longest valid field prefix (
Queryand.solve_lookup_type Query): Inside.setup_joins Query, Django walks backwards from the full list until.setup_joins Querysucceeds — here matching.names_to_path "published_at"on"Story". Every trailing segment except the final lookup (["year"]) is wrapped into a closure that invokesQuery, turning.try_transform Col(newsroom_story, newsroominto.Story .published_at) ExtractYear(Col(...)). - Terminal lookup (
Query):.build_lookup Queryconsumes any remaining transform names, then asks the left-hand expression (.build_lookup ExtractYear) for"get_lookup('gte')"— defaulting to"exact"if no lookup name was provided at all (as in"filter(priority=1)").
And notice a special-case rewrite right inside Query (lines 1451–1458): if the resolved lookup is Exact and the right-hand side is Python None, Django silently swaps the lookup for IsNull(lhs, True). That is why "Story emits "IS NULL" rather than the broken SQL "= NULL" (which evaluates to "UNKNOWN" for every row in SQL’s three-valued logic).
RegisterLookupMixin: why published_at__year__gte=2026 stays index-friendly
Both Field and Transform inherit from RegisterLookupMixin. Every class inheriting the mixin keeps a "class_lookups" dict populated by RegisterLookupMixin.
When RegisterLookupMixin resolves a name like "gte" on an expression:
- It walks the MRO of the expression or transform class itself first (
_get_lookup), checking each class’s"class_lookups"(cached per class viafunctoolson.lru_cache get_lookups). - Only if the expression class itself does not override that lookup name does
BaseExpressionfall back to its.get_lookup "output_field"'sRegisterLookupMixin— walking the MRO of the.get_lookup Fieldclass instead (so"CharField"inherits"exact","in","isnull","gte"registered onField, while"UUIDField"can override"iexact"withUUIDIExact).
Now watch what happens because ExtractYear registers YearGte (YearGte, subclass of YearLookup, YearLookup) directly onto ExtractYear:
3. Lookups, transforms, and RegisterLookupMixin
lookup_node = YearGte(ExtractYear(Col(newsroom_story, newsroom.Story.published_at)), 2026)
lookup_class=YearGte lhs_class=ExtractYear lhs_source=Col(newsroom_story, newsroom.Story.published_at) rhs=2026
year_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 "newsroom_story"."published_at" >= %s ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
year_params = ('2026-01-01 00:00:00',)
year_count = 5
published_at=None -> lookup_class=IsNull rhs=True
null_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 "newsroom_story"."published_at" IS NULL ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC params=()
null_slugs = ['zoning-board-tables-plan']
custom_lookup_dispatch = NotEqual
ne_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 "newsroom_story"."status" <> %s ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC params=(Story.Status.PUBLISHED,)
ne_slugs = ['zoning-board-tables-plan']
Look closely at "year_sql" and "year_params". There is no "EXTRACT(YEAR FROM ...)" or "django_datetime_extract" function call anywhere in the SQL! Because ExtractYear registered YearGte on itself, RegisterLookupMixin chose YearGte instead of the generic GreaterThanOrEqual on IntegerField. Inside YearLookup, whenever "rhs_is_direct_value()" is True (a literal integer like 2026 rather than an F expression), Django bypasses ExtractYear completely, reaches through the transform’s inner "lhs" straight to the raw Col, asks BaseDatabaseOperations for the UTC boundary '2026-01-01 00:, and emits "newsroom_story"."published_at" >= %s — letting the database use a B-tree index on "published_at" instead of scanning the entire table!
Lookup vs. Transform and custom registrations
The difference between a Lookup and a Transform is their output role in the AST:
- A
Transformis an expression (lhs -> transformed_expression) whose"output_field"defaults to"lhsunless overridden (for instance,.output_field" ExtractYearsets"output_field = IntegerField()"). Because aTransformreturns a value expression, you can chain multiple transforms ("published_at__date__year__gte") and even register a bilateral transform ("bilateral = True", such as"Upper"), which automatically wraps both"lhs"and"rhs"when a lookup compiles. - A
Lookup(Lookup, andBuiltinLookup,BuiltinLookup) is always a terminal boolean predicate (output_field = BooleanField()).Lookupand.process_lhs Lookupcompile both operands via.process_rhs SQLCompiler, preparing raw Python RHS values through.compile Field, while.get_db_prep_value BuiltinLookuplooks up the backend’s operator template in.get_rhs_op DatabaseWrapper(.operators DatabaseWrapper, for example,.operators "exact": "= %s","gte": ">= %s").
Because RegisterLookupMixin simply inserts into "class_lookups" and clears the class’s lookup cache (_clear_cached_class_lookups), registering a custom Lookup such as "NotEqual" ("lookup_name = 'ne'") on Field makes "status__ne=..." immediately work on every concrete field in every model — as seen in "ne_sql" above (WHERE "newsroom_story"."status" <> %s).
So far we have watched filters and lookups turn into expression nodes bound to table aliases like "newsroom_story" and "newsroom_desk". Where do those aliases come from, how does Django know which tables belong in "FROM", and why does filtering "desk__id=1" emit zero "JOIN"s? We open the Query object itself next in Inside Query: alias maps and table joins.