I have a table (Django Model) and each row/object contains a regular expression that I should evaluate over a given input to filter relevant objects.
Is there any Django ORM method to do this?
In Postgre it will be:
SELECT * FROM 'value' ~ column;
and the opposite of what I am searching for is:
Model.objects.filter(column__regex='regex')
I know that evaluating the regular expressions on the application side would give similar performance as the query, but my application design requires me to move that filter on the database side (as a proper ORM-based query).
Any ideas how can I achieve that using Django?
Thank you!
Best regards,
Advertisement
Answer
We can use .annotate(..)
to “inject” a value, and then use an F
-expression to refer to the column:
from django.db.models import CharField, Value, F Model.objects.annotate( value=Value('value', output_field=CharField()) ).filter( value__regex=F('regex') )