Creating custom Field Lookups in Django

django, django-queryset, python

Solution

As of Django 1.7, there is a simple way to implement it. Your example is actually very similar to the one from the documentation:

from django.db.models import Lookup

class AbsoluteValueLessThan(Lookup):
    lookup_name = 'lt'

    def as_sql(self, qn, connection):
        lhs, lhs_params = qn.compile(self.lhs.lhs)
        rhs, rhs_params = self.process_rhs(qn, connection)
        params = lhs_params + rhs_params + lhs_params + rhs_params
        return '%s < %s AND %s > -%s' % (lhs, rhs, lhs, rhs), params

AbsoluteValue.register_lookup(AbsoluteValueLessThan)

While registering, you can just use `Field.register_lookup(AbsoluteValueLessThan)` instead.

Problem

How do you create custom field lookups in Django? When filtering querysets, django provides a set of lookups that you can use: `__contains`, `__iexact`, `__in`, and so forth. I want to be able to provide a new lookup for my manager, so for instance, someone could say: ``` twentysomethings = Person.objects.filter(age__within5=25) ``` and get back all the `Person` objects with an age between 20 and 30. Do I need to subclass the `QuerySet` or `Manager` class to do this? How would it be implemented?

Original source