1

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?

0

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.