i've got a dict generated at somewhere like this:
d={ 'k1':'v1', 'k2':'v2', ... }
and i want to build a query like:
SomeModule.objects.filter( Q(k1=v1) | Q(k2=v2) | ... )
what should i do to build the query?
i've got a dict generated at somewhere like this:
d={ 'k1':'v1', 'k2':'v2', ... }
and i want to build a query like:
SomeModule.objects.filter( Q(k1=v1) | Q(k2=v2) | ... )
what should i do to build the query?
If you are doing "OR" queries, something like this:
from django.db.models import Q
q = Q()
for k,v in d.iteritems():
q |= Q(**{'%s__equal' % k: v})
SomeModule.objects.filter(q)
For "AND" queries it's much simpler as shown in the answer to In Django, how does one filter a QuerySet with dynamic field lookups:
SomeModule.objects.filter(**d)
You can also do it the functional way in just one line without those pesky temporary variables forced by the procedural paradigm:
SomeModule.objects.filter(reduce(Q.__or__, (Q(k=v) for k, v in d.iteritems())))