Django query case-insensitive list match

dragoon picture dragoon · Apr 19, 2010 · Viewed 16.3k times · Source

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])

Answer

Rasmus Kaj picture Rasmus Kaj · Apr 19, 2010

Unfortunatley, there are no __iin field lookup. But there is a iregex that might be useful, like so:

result = Name.objects.filter(name__iregex=r'(name1|name2|name3)')

or even:

a = ['name1', 'name2', 'name3']
result = Name.objects.filter(name__iregex=r'(' + '|'.join(a) + ')')

Note that if a can contain characters that are special in a regex, you need to escape them properly.

NEWS: In Django 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 documentation reference for details.