I have a list of names that I want to match case insensitive, is there a way to do it without using a loop like below?
a = ['name1', 'name2', 'name3']
result = any([Name.objects.filter(name__iexact=name) for name in a])
I have a list of names that I want to match case insensitive, is there a way to do it without using a loop like below?
a = ['name1', 'name2', 'name3']
result = any([Name.objects.filter(name__iexact=name) for name in a])
Unfortunatley, there are no
__iin
field lookup. But there is airegex
that might be useful, like so:or even:
Note that if a can contain characters that are special in a regex, you need to escape them properly.
NEWS: In Djano 1.7 it is possible to create your own lookups, so you can actually use
filter(name__iin=['name1', 'name2', 'name3'])
after proper initialization. See https://docs.djangoproject.com/en/1.7/ref/models/lookups/ for details.I am expanding Exgeny idea into an two liner.
Here is an example of custom User model
classmethod
to filter users by email case-insensitiveIn Postgresql you could try creating a case insensitive index as described here:
https://stackoverflow.com/a/4124225/110274
Then run a query:
Index search will run faster than the regex matching query.
Keep in mind that at least in MySQL you have to set
utf8_bin
collation in your tables to actually make them case sensitive. Otherwise they are case preserving but case insensitive. E.g.So, if portability is not crucial and you use MySQL you may choose to ignore the issue altogether.
Another way to this using django query functions and annotation