2
votes

I have been searching for a way of using Django ORM to use the SQL underscore wildcard, and do something equivalent to this:

SELECT * FROM table
WHERE field LIKE 'abc_wxyz'

Currently, I am doing:

field_like = 'abc_wxyz'
result = MyClass.objects.extra(where=["field LIKE " + field_like])

I already tried with contains() and icontains(), but that's not what I need, since what it does is adding parenthesis to the query:

SELECT * FROM table
WHERE field LIKE '%abc/_wxyz%'

Thanks!

3
What do you mean by adding paranthesis to the query? In general, on Django ORM, contains is equivalent to '%abc%', startswith is equivalent to 'abc%' and endswith is equivalent to '%abc' - Ozgur Akcali
You're right, I meant percentage character - Carolina Londoño
I didn't notice the "_" character in your query. You can use "__regex " to use a regular expression for filtering - Ozgur Akcali

3 Answers

0
votes

You can use the field__contains attribute.

for example:

MyClass.objects.filter(field__contains='abc_wxyz')

This is equivalent to:

SELECT * FROM MyClass WHERE field LIKE 'abc_wxyz'
0
votes

You can use __regex lookup to build more complex lookup expressions than __contains, __startswith or __endswith (can add "i" character to beginning of each of these to make lookups case insensitive, like icontains). In your case, I think

MyClass.objects.filter(field__regex=r'^abc.wxyz$')

Would do what you are trying to do.

0
votes

Lord Elron's answer is incorrect. Django escapes all developer supplied wildcard characters to the LIKE-type lookups. The statement is equivalent to

SELECT * FROM MyClass WHERE field LIKE '%abc/_wxyz%'

(as the OP discovered) and the underscore has no effect.

See Escaping percent signs and underscores in LIKE statements

The field lookups that equate to LIKE SQL statements (iexact, contains, icontains, startswith, istartswith, endswith and iendswith) will automatically escape the two special characters used in LIKE statements – the percent sign and the underscore.