简体   繁体   English

搜索多个字段django

[英]search multiple fields django

I'm trying to build a search system, and I want to search by multiple fieldsname, state, city, in my django models. 我正在尝试构建一个搜索系统,我想在Django模型中按多个字段名称,州,城市进行搜索。 I wrote the below code, yet I've been unable to figure out how to go about it. 我写了下面的代码,但是我一直无法弄清楚该怎么做。 I use Q but it seems not working: 我使用Q,但似乎无法正常工作:

views.py: 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())

Have a think about what 考虑一下

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

becomes with eg [('toBuy', 'bread'), ('name__contains', 'bread')] . [('toBuy', 'bread'), ('name__contains', 'bread')] It becomes 它成为了

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

which is obviously wrong syntax, since Q rather needs kwargs than a tuple: 这显然是错误的语法,因为Q宁愿使用kwarg而不是元组:

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

that's where the ** operator comes to the rescue. 这就是**运算符进行救援的地方。 If you get data like this: 如果您得到这样的数据:

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

which may be accomplished by simply changing the conditions assignment you can then do 只需更改conditions分配即可完成

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

which translates in the particular case to 在特定情况下会转换为

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

which is exactly what we need. 这正是我们所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM