我有一个字符串列表,它将动态生成。所以它的长度可变:
keywords = ['apples','oranges','bananas']
我有一个模型Fruitsalad,带有字段'description'。让我们说我想在'描述'字段中找到所有Fruitsalads与'苹果','橙子'或'香蕉'
results = Fruitsalad.objects.filter(Q(description__icontains=keywords[0]) | Q(description__icontains=keywords[1] | Q(description__icontains=keywords[2])
如果我事先不知道“关键字”列表会有多长时间,我怎么能生成上述查询呢?
答案 0 :(得分:0)
你应该迭代你的数组,并在每个结果上进行联合
allresults = Fruitsalad.objects.all()
keywords = ['apples','oranges','bananas']
queryset = None
for keyword in keywords:
if queryset == None:
queryset = allresults.filter(description__icontains=keyword)
else:
queryset = queryset.union(allresults.filter(description__icontains=keyword))
#here are the desired results
print(queryset)