Chris
Chris

Reputation: 6392

Use Django ORM Postgresql regex when the regex is in the database and the value is a string

I understand how to do Postgresql regular expression searches through the Django ORM when I am passing the regular expression. What is the equivalent when the regular expression is in the database table, and I am passing the string?

For example, the following Postgresql and Django ORM queries are equivalent:

INSERT INTO StringValues (val) VALUES ('abc');

SELECT * FROM StringValues WHERE val ~* '^[a-z]{3}$';

# is the same as

StringValues.objects.filter(val__regex=r'^[a-z]{3}$')

How would can you do the following query in Django?

INSERT INTO StringValues (val) VALUES ('^[a-z]{3}$');

SELECT * FROM StringValues WHERE 'abc' ~* val;

I.E. the regular expression is in the table and I want the row that matches my string.

In my specific case performance isn't an issue - there will be probably under 100 rows to compare - but comments on the performance of this also welcome thanks, if compilation of every regex is a really bad idea.

Upvotes: 5

Views: 2329

Answers (1)

Chris
Chris

Reputation: 6392

StringValues.objects.extra(where=["'abc' ~ val"])

Upvotes: 5

Related Questions