Django 6.1.3

8.3 From Python to SQL

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.objects.filter(published_at__year__gte=2026)", 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.build_filter 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:

  1. Longest valid field prefix (Query.solve_lookup_type and Query.setup_joins): Inside Query.setup_joins, Django walks backwards from the full list until Query.names_to_path succeeds — here matching "published_at" on "Story". Every trailing segment except the final lookup (["year"]) is wrapped into a closure that invokes Query.try_transform, turning Col(newsroom_story, newsroom.Story.published_at) into ExtractYear(Col(...)).
  2. Terminal lookup (Query.build_lookup): Query.build_lookup consumes any remaining transform names, then asks the left-hand expression (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.build_lookup (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.objects.filter(published_at=None)" 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.register_lookup.

When RegisterLookupMixin.get_lookup resolves a name like "gte" on an expression:

Now watch what happens because ExtractYear registers YearGte (YearGte, subclass of YearLookup, YearLookup) directly onto ExtractYear:

Recorded on Django 6.1.3 ch08-sql script
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.get_lookup chose YearGte instead of the generic GreaterThanOrEqual on IntegerField. Inside YearLookup.as_sql, 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.year_lookup_bounds_for_datetime_field for the UTC boundary '2026-01-01 00:00: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:

Because RegisterLookupMixin.register_lookup 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.