0%

Django:自定义Lookup

Django已经内置了许多lookup用来检索数据,这些lookups能满足绝大部分应用场景。 但有些时候我们需要自定义lookup用来满足特定的需求。

假设需要实现如下查询需求:

1
select * from test_tbl reverse(content) like '54321%';  -- postgresql

定义如下Lookup

1
2
3
4
5
6
7
8
9
10
11
from django.db.models import Field
from django.db.models.lookups import Lookup

@Field.register_lookup
class ReversePattern(Lookup):
lookup_name = 'reverse'

def as_sql(self, compiler, connection):
lhs, _ = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
return 'reverse(%s) like %s' % (lhs, rhs), [''.join(reversed(str(rhs_params[0]))) + '%']

查询:

1
Test.objects.filter(content__reverse='12345')