tags:

views:

166

answers:

2

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?

+2  A: 

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)
Van Gale
A: 

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())))
Ilya Semenov