Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can django sql queries use case insensitive and contains at the same time?

Tags:

python

django

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.

like image 694
demoslam Avatar asked May 09 '11 10:05

demoslam


People also ask

How do you make a case insensitive in SQL query?

Case insensitive SQL SELECT: Use upper or lower functions or this: select * from users where lower(first_name) = 'fred'; As you can see, the pattern is to make the field you're searching into uppercase or lowercase, and then make your search string also be uppercase or lowercase to match the SQL function you've used.

Is Django case sensitive?

So, the programmer has told Django explicitly, 'I want case-insensitive comparison', and Django tells MySQL, 'We want default comparison'. This is not field_icontains but rather some field_usingdefaultsettingscontains. So, case-sensitivity is explicitly requested, while case-insensitivity is implied.

How do you query case insensitive?

Introduction to SQL Case Insensitive SQL Case insensitivity is to use the query statements and the keywords tables and columns by specifying them in capital or small letters of alphabets. SQL keywords are by default set to case insensitive that means that the keywords are allowed to be used in lower or upper case.


1 Answers

Use:

User.objects.filter(username__icontains='ab') 
like image 62
lprsd Avatar answered Sep 20 '22 23:09

lprsd