django 自定义查询器

场景描述

Django 提供了各种各样的 内置查询器 (例如exact 和 icontains)

创建 Not Like 表达式

from django.db.models.fields import Field
from django.db.models.lookups import IEndsWith

@Field.register_lookup
class NotIEndsWith(IEndsWith):
lookup_name = 'notiendswith'

def get_rhs_op(self, connection, rhs):
  return 'NOT ' + connection.operators['iendswith'] % rhs

使用方法

In [1]: import logging; logging.getLogger('django').setLevel(logging.DEBUG) # to see the output
In [2]: from django.contrib.auth import models
In [3]: models.User.objects.filter(email__notiendswith='@example.com')
Out[3]: 03-06 12:13 django.db.backends DEBUG    (0.000) SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."email" NOT LIKE '%@example.com' ESCAPE '' LIMIT 21; args=(u'%@example.com',)
<QuerySet [<User: someuser>]>

官方文档参考[src] https://docs.djangoproject.com/zh-hans/2.2/howto/custom-lookups/