Skip to content Skip to sidebar Skip to footer

Sqlalchemy - Build Query Filter Dynamically From Dict

So I have a dict passed from a web page. I want to build the query dynamically based on the dict. I know I can do: session.query(myClass).filter_by(**web_dict) However, that onl

Solution 1:

You're on the right track!

First thing you want to do different is access attributes using getattr, not __dict__; getattr will always do the right thing, even when (as may be the case for more convoluted models) a mapped attribute isn't a column property.

The other missing piece is that you can specify filter() more than once, and just replace the old query object with the result of that method call. So basically:

q = session.query(myClass)
for attr, value in web_dict.items():
    q = q.filter(getattr(myClass, attr).like("%%%s%%" % value))

Post a Comment for "Sqlalchemy - Build Query Filter Dynamically From Dict"