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%';
contains and icontains mentioned by falsetru make queries like SELECT ... WHERE headline LIKE '%pattern%
Along with them, you might need these ones with similar behavior:startswith, istartswith, endswith, iendswith
making
SELECT ... WHERE headline LIKE 'pattern%
or
SELECT ... WHERE headline LIKE '%pattern
This can be done with Django's custom lookups. I have made the lookup into a Django-like-lookup application. After installing it the __like
lookup with the %
and _
wildcards will be enabled.
All the necessary code in the application is:
from django.db.models import Lookupfrom django.db.models.fields import Field@Field.register_lookupclass Like(Lookup): lookup_name = 'like' def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params return '%s LIKE %s' % (lhs, rhs), params