django icontains与__in查找 [英] 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)
不可能混合图标和__in查找。
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)
任何想法?
PD:我发布的查询不起作用,这只是一种表达我需要的方式(以防万一) p>
P.D.: The queries I posted don't work, it's just a way to express what I need (just in case heh)
推荐答案
您可以创建查询集 Q 构造函数查询/#complex-lookups-with-q-objects,并将它们与 |
运算符来获取他们的联合:
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)
而与 iexact
而不是 icontains
相似。)
这篇关于django icontains与__in查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!