3

see what I have:

> bar = [(u'code__regex', u'^[^J]'), (u'active__exact', u'0'), (u'type__id__exact', u'E01')]

There are the fields/values that I want to use to filter the model Foo.

> #want to have this equivalent:
> Foo.objects.filter(bar)

Thanks!

2 Answers 2

8
Foo.objects.filter(**dict(bar))

This isn't a django issue, this is a python issue. You want to pass the keyword pairs as keyword arguments (kwargs) to the filter. Your bar is perfect as a kwarg set, so the dict(bar) converts it to the dictionary, and the ** prefix informs the python parser that the dictionary is to be interpreted as keyword arguments by the receiver.

Stack overflow entry Understanding kwargs in Python covers this in more detail.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! it raises a TypeError: filter() keywords must be strings. Because the args comes in unicode, if we convert them to strings this works nice!.
3

You didn't say if you want it in AND or OR. If AND is ok then you can simply convert that list into a dictionary and pass it to filter:

Foo.objects.filter(**dict(bar))

1 Comment

OR is trickier: Foo.objects.filter(reduce(operator.__or__, [Q(**dict([i])) for i in bar])) is the shortest way I know to achieve this. You have to import both django.db.models.Q and operator.

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.