← Back to Django, page 5

django-0098 · Hard senior

How do you extend the Django ORM with a custom lookup, a custom Transform and a custom model field?

A Lookup subclass defines how a filter operator renders to SQL (as_sql returns the SQL fragment and parameters) and is registered on a field class with register_lookup; a Transform wraps a column in a function and can be chained before other lookups; a custom Field customises conversion with from_db_value, to_python and get_prep_value. Together they let filter(score__abs__gt=5) or filter(name__ne='x') read naturally while the database does the work.

Full answer

Lookup:

python
@CharField.register_lookup
class NotEqual(Lookup):
    lookup_name = "ne"
    def as_sql(self, compiler, connection):
        lhs, lhs_params = self.process_lhs(compiler, connection)
        rhs, rhs_params = self.process_rhs(compiler, connection)
        return f"{lhs} <> {rhs}", [*lhs_params, *rhs_params]

Usage: Student.objects.filter(name__ne="Asha"). process_lhs and process_rhs produce SQL and parameters safely, so values are always bound parameters, never concatenated. Never format user values into the SQL string.

Transform:

python
@IntegerField.register_lookup
class Abs(Transform):
    lookup_name = "abs"
    function = "ABS"

filter(delta__abs__gt=5) becomes ABS(delta) > 5. Because a transform returns a field-like expression, it can be chained with other lookups and transforms. Set output_field when the result type differs from the input (for example Length returns an integer).

Custom field: subclass Field or an existing field and override:

  • db_type() or get_internal_type() (the column type),
  • get_prep_value() (Python to database),
  • from_db_value() (database to Python on loading),
  • to_python() (forms and deserialisation), formfield(), deconstruct() (so migrations can recreate the field).

Rules and cautions:

  • Registration applies to all fields of that class in the process; register in AppConfig.ready() or at import time of a module that is always loaded.
  • Keep SQL portable or branch with as_postgresql and as_sqlite methods.
  • Functional indexes (Index(Abs("delta"), ...)) pair with transforms for speed.
  • Think before building: many needs are met by Func expressions, annotate, or built-in lookups. Custom fields are worth it for real domain types (money, a range, an encrypted value) that appear on several models.
python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import models, connection
from django.db.models import Lookup, Transform


@models.CharField.register_lookup
class NotEqual(Lookup):
    lookup_name = "ne"

    def as_sql(self, compiler, connection):
        lhs, lhs_params = self.process_lhs(compiler, connection)
        rhs, rhs_params = self.process_rhs(compiler, connection)
        return f"{lhs} <> {rhs}", [*lhs_params, *rhs_params]


@models.IntegerField.register_lookup
class Abs(Transform):
    lookup_name = "abs"
    function = "ABS"


class TagsField(models.TextField):
    """Stores a Python list as comma-separated text."""

    def from_db_value(self, value, expression, connection):
        return [] if not value else value.split(",")

    def to_python(self, value):
        return value if isinstance(value, list) else self.from_db_value(value, None, None)

    def get_prep_value(self, value):
        return ",".join(value) if value else ""


class Reading(models.Model):
    sensor = models.CharField(max_length=20)
    delta = models.IntegerField()
    tags = TagsField(blank=True)

    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Reading)

Reading.objects.create(sensor="lab", delta=-8, tags=["temp", "room-1"])
Reading.objects.create(sensor="hall", delta=3, tags=[])
Reading.objects.create(sensor="gym", delta=12, tags=["humidity"])

print([r.sensor for r in Reading.objects.filter(sensor__ne="hall").order_by("id")])
print([r.sensor for r in Reading.objects.filter(delta__abs__gt=5).order_by("id")])
print(str(Reading.objects.filter(delta__abs__gt=5).query).split("WHERE")[1].strip())
print(Reading.objects.get(sensor="lab").tags, Reading.objects.get(sensor="hall").tags)
print(list(Reading.objects.annotate(size=Abs("delta")).order_by("-size").values_list("sensor", "size")))

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['lab', 'gym'] ['lab', 'gym'] ABS("school_reading"."delta") > 5 ['temp', 'room-1'] [] [('gym', 12), ('lab', 8), ('hall', 3)]

Key points

  • Lookup defines an operator; Transform wraps a column in a function
  • Use process_lhs and process_rhs so values stay parameterised
  • register_lookup attaches to a field class
  • Custom fields override prep, load and deconstruct methods
  • Prefer Func or annotations when a one-off is enough

Common mistakes

  • Formatting values into the SQL string and creating SQL injection
  • Forgetting output_field for transforms that change the type
  • Registering lookups in a module that is not always imported
  • Writing a custom field without deconstruct(), breaking migrations
  • Building a custom field where a Func or annotation would do

Follow-ups

  • How do you make a lookup database-specific?
  • How would you create an index for a transform?
  • What does from_db_value not run for?

Tips

  • Distinguish lookup, transform and field
  • Mention parameterised SQL
  • Mention deconstruct()