搜索多个字段django

时间:2015-08-14 17:08:29

标签: python django django-views

我正在尝试建立一个搜索系统,我想在我的django模型中搜索多个fieldsname,state,city。我写了下面的代码,但我一直无法弄清楚如何去做。我使用Q但似乎不起作用:

views.py:

def data_consulting(request):
    if request.method == 'POST':
          form = FilterForm(request.POST)
          if form.is_valid():
                conditions = [('toBuy', form.cleaned_data['toBuy']), ('name__contains', form.cleaned_data['searchName']),(('price__gte', form.cleaned_data['searchPriceBegin']), ('price__lte',form.cleaned_data['searchPriceEnd'])),(('calories__gte', form.cleaned_data['searchCalorieBegin']), ('calories__lte', form.cleaned_data['searchCalorieEnd'])), (('date__gte',form.cleaned_data['DateBegin']), ('date__lte', form.cleaned_data['DateEnd']))]
                all_products = Product.objects.filter(reduce(operator.or_, [Q(condition) for condition in conditions]))
                send = True
                all_products = Product.objects.filter(reduce(operator.or_, [Q(condition) for condition in conditions]))
           else:
                form = FilterForm()
                all_products = Product.objects.all()
    return render(request, 'mealManager/data_consulting.html', locals())

1 个答案:

答案 0 :(得分:1)

考虑一下

reduce(operator.or_, [Q(condition) for condition in conditions])

成为例如[('toBuy', 'bread'), ('name__contains', 'bread')]。它变成

Q(('toBuy', 'bread')) | Q(('name_contains', 'bread'))

这显然是错误的语法,因为Q而不是needs kwargs而不是元组:

Q(toBuy='bread') | Q(name__contains='bread')

**运营商拯救的地方。如果你得到这样的数据:

[{'toBuy': 'bread'}, {'name__contains': 'bread'}]

可以通过简单地更改您可以执行的conditions作业来完成

reduce(operator.or_, [Q(**condition) for condition in conditions])

在特定情况下转换为

Q(toBuy='bread') | Q(name__contains='bread')

这正是我们所需要的。