Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 363
MFB Avatar asked Sep 30 '11 01:09

MFB


1 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)) 
like image 163
SingleNegationElimination Avatar answered Sep 17 '22 18:09

SingleNegationElimination