I am writing a view which searches my models db depending on search fields selected by the user. The basic code is something like:
def search(request):
if submit in request.POST:
...
kwargs = {}
if request.POST['field1']:
kwargs['field1__icontains'] = request.POST['field1']
if request.POST['field2']:
kwargs['field2__icontains'] = request.POST['field2']
...
results_list = Mymodel.objects.filter(**kwargs)
...
Of course this is fine if my query is all AND statements, but if I need to throw an OR in there – is it possible? For example if I needed field2__icontains = request.POST['field2'] OR field3__icontains = request.POST['field2']
Build up a
Q()object instead of a dictionary as you work through your fields. Then you canandandoras you wish.