I am writing a simple search form for a specific model. Let me name the Orchard model and give it the apples , oranges and pears for demonstration only.
Thus, the form does not require filling all the fields. So you can search for apples and oranges , but not pears. I need to filter like this:
Orchard.objects.filter(apples=request.GET.get('apples'), oranges=request.GET.get('oranges'), pears=request.GET.get('pears'))
but if pears empty, results are never returned.
My first thought was to use Q objects, something like this:
from django.db.models import Q options = {} options['apples'] = request.GET.get('apples') options['oranges'] = request.GET.get('oranges') options['pears'] = request.GET.get('pears') queries = None for key in options: if options[key] != u'': if queries: queries &= Q(key=options[key])
The problem occurs in the marked lines. I obviously canβt just use the βkeyβ as the attribute keyword, because it does not accept a string, it takes essentially a variable.
So ... how do I get around this?
If there is a known solution to this problem that does not include Q That would also be helpful.
source share