django icontains with __in lookup

前端 未结 3 1908
庸人自扰
庸人自扰 2020-12-05 01:14

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\", \"servi         


        
3条回答
  •  天命终不由人
    2020-12-05 01:26

    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.)

提交回复
热议问题