Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to do a case-insensitive IN query in Django?

Nearly every kind of lookup in Django has a case-insensitive version, EXCEPT in, it appears.

This is a problem because sometimes I need to do a lookup where I am certain the case will be incorrect.

Products.objects.filter(code__in=[user_entered_data_as_list])

Is there anything I can do to deal with this? Have people come up with a hack to work around this issue?

like image 849
Jordan Reiter Avatar asked Mar 02 '10 03:03

Jordan Reiter


People also ask

Is Django case sensitive?

Django model names are not case insensitive, but basically, Django creates a lowercase table name from the app and model names.

How do you make a search case insensitive?

Case insensitive SQL SELECT: Use upper or lower functions 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.

What are QuerySets in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

What does .values do in Django?

The values_list() method allows you to return only the columns that you specify.


1 Answers

I worked around this by making the MySQL database itself case-insensitive. I doubt that the people at Django are interested in adding this as a feature or in providing docs on how to provide your own field lookup (assuming that is even possible without providing code for each db backend)

Here is one way to do it, admittedly it is clunky.

products = Product.objects.filter(**normal_filters_here)
results = Product.objects.none()
for d in user_entered_data_as_list:
    results |= products.filter(code__iexact=d)
like image 195
Jordan Reiter Avatar answered Nov 13 '22 16:11

Jordan Reiter