ORM custom lookup

Пример создание ORM фильтра для django для задачи - выбрать по значению не равному 5
Snippet code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# Filter code
from django.db.models import 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)
        params = lhs_params + rhs_params
        return '%s <> %s' % (lhs, rhs), params


# Usage example
from django.db.models import Field
Field.register_lookup(NotEqual)

results = Model.objects.exclude(a=True, x__ne=5)
The end