简体   繁体   中英

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

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')] . It becomes

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

which is obviously wrong syntax, since Q rather needs kwargs than a tuple:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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