Fix Python – sql “LIKE” equivalent in django query


Asked By – Aswin Murugesh

What is the equivalent of this SQL statement in django?

SELECT * FROM table_name WHERE string LIKE pattern;

How do I implement this in django? I tried

result = table.objects.filter( pattern in string )

But that did not work. How do i implement this?

Now we will see solution for issue: sql “LIKE” equivalent in django query


Use __contains or __icontains (case-insensitive):

result = table.objects.filter(string__contains='pattern')

The SQL equivalent is

SELECT ... WHERE string LIKE '%pattern%';

@Dmitri’s answer below covers patterns like ‘pattern%’ or ‘%pattern’

This question is answered By – falsetru

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0