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

# 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` (`django/db/models/options.py:Options`), `"year"` is a **`Transform`** (`django/db/models/lookups.py:Transform`) that wraps a `Col` (`django/db/models/expressions.py:Col`) into a new expression, and `"gte"` is a **`Lookup`** (`django/db/models/lookups.py: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` (`django/db/models/sql/query.py: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/db/models/sql/query.py:Query.setup_joins`), Django walks backwards from the full list until `Query.names_to_path` (`django/db/models/sql/query.py: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` (`django/db/models/sql/query.py:Query.try_transform`), turning `Col(newsroom_story, newsroom.Story.published_at)` into `ExtractYear(Col(...))` (`django/db/models/functions/datetime.py:ExtractYear`).
2. **Terminal lookup (`Query.build_lookup`):** `Query.build_lookup` (`django/db/models/sql/query.py: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` (`django/db/models/lookups.py:Exact`) and the right-hand side is Python `None`, Django silently swaps the lookup for `IsNull(lhs, True)` (`django/db/models/lookups.py:IsNull`). 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` (`django/db/models/fields/__init__.py:Field`) and `Transform` inherit from **`RegisterLookupMixin`** (`django/db/models/query_utils.py:RegisterLookupMixin`). Every class inheriting the mixin keeps a `"class_lookups"` dict populated by `RegisterLookupMixin.register_lookup` (`django/db/models/query_utils.py:RegisterLookupMixin.register_lookup`).

When `RegisterLookupMixin.get_lookup` (`django/db/models/query_utils.py:RegisterLookupMixin.get_lookup`) 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 via `functools.lru_cache` on `get_lookups`).
- Only if the expression class itself does not override that lookup name does `BaseExpression.get_lookup` fall back to its `"output_field"`'s `RegisterLookupMixin.get_lookup` — walking the MRO of the `Field` class instead (so `"CharField"` inherits `"exact"`, `"in"`, `"isnull"`, `"gte"` registered on `Field`, while `"UUIDField"` can override `"iexact"` with `UUIDIExact`).

Now watch what happens because `ExtractYear` registers **`YearGte`** (`django/db/models/lookups.py:YearGte`, subclass of `YearLookup`, `django/db/models/lookups.py:YearLookup`) directly onto `ExtractYear`:

```text recording=ch08-sql
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` (`django/db/models/lookups.py: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:

- A **`Transform`** (`django/db/models/lookups.py:Transform`) is an expression (`lhs -> transformed_expression`) whose `"output_field"` defaults to `"lhs.output_field"` unless overridden (for instance, `ExtractYear` sets `"output_field = IntegerField()"`). Because a `Transform` returns 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`** (`django/db/models/lookups.py:Lookup`, and `BuiltinLookup`, `django/db/models/lookups.py:BuiltinLookup`) is always a terminal boolean predicate (`output_field = BooleanField()`). `Lookup.process_lhs` and `Lookup.process_rhs` compile both operands via `SQLCompiler.compile`, preparing raw Python RHS values through `Field.get_db_prep_value`, while `BuiltinLookup.get_rhs_op` looks up the backend's operator template in `DatabaseWrapper.operators` (`django/db/backends/sqlite3/base.py:DatabaseWrapper.operators`, for example, `"exact": "= %s"`, `"gte": ">= %s"`).

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