Last Updated: May 22, 2022
·
3.762K
· pykler

Creating your own django lookup function

Although after creating this, found that this specifically is not needed and can be replaced with a Q function expression, the ability to create a custom lookup was interesting. Here is a small example for creating "NOT LIKE" expression for django's ORM.

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

You can use it as follows

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>]>