[Django]-How to filter model with a list containing the field and the value?

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.

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

Leave a comment