How can I perform a regex lookup with the regular expression being stored in a field value?

时间:2015-07-28 23:27:24

标签: regex django django-models

Given the following model:

from django.db import models
from django.conf import settings

class UserMessage(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    path = models.CharField(max_length=255)
    message = models.TextField()

And given the following instance of the model:

UserMessage.objects.create(
    user=request.user,
    path='^/dashboard/(.*)+$',
    message='Welcome to your dashboard!'
)

I want to be able to perform a lookup of the current request path against the value of UserMessage.path. This means that I need to have 'path' on the right side of my query, e.g.:

SELECT * FROM user_message WHERE '/dashboard/foo/' ~ path;

However, the Django ORM's regexp lookup produces the opposite order, e.g.:

SELECT * FROM user_message WHERE path ~ '/dashboard/foo/';

Is there a way I can easily reverse this for my desired result, using an ORM lookup? Or is this better suited for a .extra() or custom lookup expression?

2 个答案:

答案 0 :(得分:1)

额外()

UserMessage.objects.extra(where=['%s ~ path'], params=[request.path])

自定义查找

models.py

from django.db.models import Lookup

@models.CharField.register_lookup
class NotEqual(Lookup):
    lookup_name = 'test'

    def as_postgresql(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' % (rhs, lhs), params

用法:UserMessages.objects.get(path__test=request.path)

答案 1 :(得分:0)

对于SQL,执行正则表达式的类似查询将是:

@CharField.register_lookup
class Matches(Lookup):
    lookup_name = 'matches'

    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 REGEXP %s' % (rhs, lhs), params

一起使用
UserMessage.objects.get(path__matches=request.path)