Home > Net >  Diango matching a string with a regex field
Diango matching a string with a regex field

Time:01-03

In django, if we have a regex and look for a rows whose a field is matching with a regex, it will be something like this:

MyAudience.objects.filter(email__iregex=f'^({'|'.join(emails)})$')

But what if I want to do it the other way?

Let's say I have a string:

email = '[email protected]'

and in my model AudienceFilter, I have a field pattern. This column keeps the regex for the model. I want to find with patterns do match my string? How can I do that?

AudienceFilter.objects.filter(pattern__?????=email)

CodePudding user response:

You can inject the value as an alias, and then annotate:

from django.db.models import F, Value

AudienceFilter.objects.alias(email=Value(email)).filter(
    email__iregex=F('pattern')
)
  • Related