Reputation: 1162
When using MultopleChoiceField in django how can a query for all items selected be created? By using:
return_queryset = model_name.objects.filter(Q(Column_name=request.POST.getlist('Column_name')[0])|Q(Column_name=request.POST.getlist('Column_name')[1])
It will return the or statement but only if you have the correct number of items selected. Is there a shortcut that will allow any number of items to be selected?
You can stack querysets on top of one another, but is there a way to stack or querysets as well? Thanks.
Upvotes: 0
Views: 59
Reputation: 37364
To answer your specific question about stacking or
clauses - in the general case you can combine Q objects using the functional label for |
in the built-in operator
module.
import operator
return_queryset = model_name.objects(filter(reduce(operator.or_,
(Q(Column_name=name) for name in request.POST.getlist('Column_name')))))
But for this specific case I would use in
:
return_queryset = model_name.objects.filter(Column_name__in=request.POST.getlist('Column_name'))
Upvotes: 1