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?
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? 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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With