Skip to content
Advertisement

django icontains with __in lookup

So I want to find any kind of matching given some fields, so for example, this is what I would like to do:

possible_merchants = ["amazon", "web", "services"]
# Possible name --> "Amazon Service"
Companies.objects.filter(name__icontains__in=possible_merchants)

sadly it is not possible to mix icontains and the __in lookup.

It seems to be a pretty complex query so if at least I could ignore case the name that would be enough, for example:

Companies.objects.filter(name__ignorecase__in=possible_merchants)

Any ideas?

P.D.: The queries I posted don’t work, it’s just a way to express what I need (just in case heh)

Advertisement

Answer

You can create querysets with the Q constructor and combine them with the | operator to get their union:

from django.db.models import Q

def companies_matching(merchants):
    """
    Return a queryset for companies whose names contain case-insensitive
    matches for any of the `merchants`.
    """
    q = Q()
    for merchant in merchants:
        q |= Q(name__icontains = merchant)
    return Companies.objects.filter(q)

(And similarly with iexact instead of icontains.)

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement