sql "LIKE" equivalent in django query
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop
--
Chapters
00:00 Sql &Quot;Like&Quot; Equivalent In Django Query
00:27 Accepted Answer Score 321
00:55 Answer 2 Score 56
01:34 Answer 3 Score 30
02:00 Answer 4 Score 9
02:14 Answer 5 Score 4
02:59 Thank you
--
Full question
https://stackoverflow.com/questions/1814...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #sql #django #djangomodels #djangoqueryset
#avk47
ACCEPTED ANSWER
Score 326
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'
ANSWER 2
Score 56
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
ANSWER 3
Score 9
result = table.objects.filter(string__icontains='pattern')
Case insensitive search for string in a field.
ANSWER 4
Score 5
In order to preserve the order of the words as in the sql LIKE '%pattern%' statement I use iregex, for example:
qs = table.objects.filter(string__iregex=pattern.replace(' ', '.*'))
string methods are immutable so your pattern variable will not change and with .* you'll be looking for 0 or more occurrences of any character but break lines.
By using the following to iterate over the pattern words:
qs = table.objects
for word in pattern.split(' '):
qs = qs.filter(string__icontains=word)
the order of the words in your pattern will not be preserved, for some people that could work but in the case of trying to mimic the sql like statement I'll use the first option.