How can django sql queries use case insensitive and contains at the same time?
Question:
Suppose I have two users with username ‘AbA’ and ‘aBa’ in the database.
My query word is ‘ab’.
I used
User.objects.filter(username__contains='ab')
and
User.objects.filter(username__iexact='ab')
These two queries get empty result. However, I want to use something like username__contains__iexact='ab'
that can retrieve both ‘AbA’ and ‘aBa’.
Anyone know how to resolve this problem? Thanks.
Answers:
Use:
User.objects.filter(username__icontains='ab')
icontains
is case-insensitive – http://docs.djangoproject.com/en/dev/ref/models/querysets/#std:fieldlookup-icontains
Suppose I have two users with username ‘AbA’ and ‘aBa’ in the database.
My query word is ‘ab’.
I used
User.objects.filter(username__contains='ab')
and
User.objects.filter(username__iexact='ab')
These two queries get empty result. However, I want to use something like username__contains__iexact='ab'
that can retrieve both ‘AbA’ and ‘aBa’.
Anyone know how to resolve this problem? Thanks.
Use:
User.objects.filter(username__icontains='ab')
icontains
is case-insensitive – http://docs.djangoproject.com/en/dev/ref/models/querysets/#std:fieldlookup-icontains