Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I chain Django's "in" and "iexact" queryset field lookups?

I have a list of names, e.g.:

name_list = ['Alpha', 'bEtA', 'omegA']

Currently I have the following queryset:

MyModel.objects.filter(name__in=name_list)

I would like to be able to filter the names in a case-insensitive fashion. My first thought was to use the iexact field lookup but it doesn't seem to work with in. How can I use the iexact with the in field lookup for my queryset? Or is there an alternate way to perform this query?

like image 605
Derek Kwok Avatar asked Feb 16 '13 06:02

Derek Kwok


People also ask

How do I do a not equal in Django QuerySet filtering?

To answer your specific question, there is no "not equal to" but that's probably because django has both "filter" and "exclude" methods available so you can always just switch the logic round to get the desired result.

What is difference between contains and Icontains in Django?

What is difference between contains and Icontains in Django? Definition and Usage The contains lookup is used to get records that contains a specified value. The contains lookup is case sensitive. For a case insensitive search, use the icontains lookup.

What is __ in Django ORM?

Django Field Lookups Managers and QuerySet objects comes with a feature called lookups. A lookup is composed of a model field followed by two underscores ( __ ) which is then followed by lookup name.


1 Answers

Here's my solution, which uses Q objects instead:

name_list = ['Alpha', 'bEtA', 'omegA']
q_list = map(lambda n: Q(name__iexact=n), name_list)
q_list = reduce(lambda a, b: a | b, q_list)
MyModel.objects.filter(q_list)
like image 73
Derek Kwok Avatar answered Sep 28 '22 06:09

Derek Kwok