1

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 = 'abc@example.com'

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)
barej
  • 1,330
  • 3
  • 25
  • 56

1 Answers1

0

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')
)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555