Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 331
Joey Wilhelm Avatar asked Sep 01 '25 17:09

Joey Wilhelm


1 Answers

extra()

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

Custom lookup

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

Usage: UserMessages.objects.get(path__test=request.path)

like image 174
2 revsf43d65 Avatar answered Sep 04 '25 08:09

2 revsf43d65