Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query case-insensitive list match

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]) 
like image 838
dragoon Avatar asked Apr 19 '10 12:04

dragoon


2 Answers

In Postgresql you could try creating a case insensitive index as described here:

https://stackoverflow.com/a/4124225/110274

Then run a query:

from django.db.models import Q name_filter = Q() for name in names:     name_filter |= Q(name__iexact=name) result = Name.objects.filter(name_filter) 

Index search will run faster than the regex matching query.

like image 25
Evgeny Avatar answered Sep 22 '22 06:09

Evgeny


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.

like image 58
Rasmus Kaj Avatar answered Sep 21 '22 06:09

Rasmus Kaj