[Answered ]-Combine __in and contains query filter to make a more complex filter in django

2👍

It doesn’t seem possible with normal queryset to me, I guess you need to iterate through the list and find the matches, something like:

from django.db.models import Q     

qs = User.objects.all()
for fullname in list_of_names:
    firstname, lastname = fullname.split()
    qs = qs.filter(
        Q(first_name__icontains = firstname), 
        Q(last_name__icontains = lastname)
    )

Another option would be using raw query which can be okay for this case, the query would be something like:

SELECT * FROM users WHERE CONCAT(firstname, ' ', lastname) IN (list_of_name)

But this is not case insensitive and you should try to avoid raw query anyway.

Leave a comment