Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
842 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...