How to filter a django queryset using case insensitive __in?

Question:

I have a model:

class Skill(models.Model):
    name = models.CharField(max_length=120)
    icon = models.CharField(max_length=20)
    color = models.CharField(max_length=7)

I want to do the following filter, but case insensitive:

skill_names = ['Code Quality', 'Analytical Thinking', 'Productivity', 'Communication']
Skill.objects.filter(name__in=skill_names)
Asked By: Tanvir Ahmed

||

Answers:

Try this:

from django.db.models import Q

skill_names = ['Code Quality', 'Analytical Thinking', 'Productivity', 'Communication']

query = Q()

for skill in skill_names:
    query |= Q(name__contains=skill)

Skill.objects.filter(query)

Answered By: Rakesh

I had similar problem and this helped me

from operator import or_
from functools import reduce
from django.db.models import Q

skill_names = ['Code Quality', 'Analytical Thinking', 'Productivity', 'Communication']
skill_filter = reduce(
    or_, (Q(name__icontains=skill) for skill in skill_names)
)
Skill.objects.filter(skill_filter)
Answered By: Shubham Jha
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.