How do you create custom field lookups in Django?
When filtering querysets, django provides a set of lookups that you can use: __contains
, __iexa
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.