简体   繁体   English

SQLAlchemy - 从dict动态构建查询过滤器

[英]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. 我想基于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: 我最好尝试使用__dict__属性:

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. 任何帮助都是极好的。

You're on the right track! 你走在正确的轨道上!

First thing you want to do different is access attributes using getattr , not __dict__ ; 你要做的第一件事就是使用getattr访问属性,而不是__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. getattr将始终做正确的事情,即使(对于更复杂的模型可能是这种情况),映射属性不是列属性。

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. 另一个缺失的部分是你可以多次指定filter() ,只需用该方法调用的结果替换旧的查询对象。 So basically: 所以基本上:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM