Search code examples
pythonsqldjangodjango-modelsdjango-orm

What is the SQL ''LIKE" equivalent on Django ORM queries?


What is the equivalent of the following SQL statement in Django?

SELECT * FROM table_name WHERE string LIKE pattern;

I tried this:

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

but it didn't work. How can I implement it?


Solution

  • 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'