SQLAlchemy – build query filter dynamically from dict

Question:

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 only works when the values are an exact match. I need to do ‘like’ filtering. My best attempt using the __dict__ attribute:

for k,v in web_dict.items():
    q = session.query(myClass).filter(myClass.__dict__[k].like('%%%s%%' % v))

Not sure how to build the query from there. Any help would be awesome.

Asked By: MFB

||

Answers:

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))
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.