SQLAlchemy - 从 dict 动态构建查询过滤器 [英] SQLAlchemy - build query filter dynamically from dict

查看:39
本文介绍了SQLAlchemy - 从 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)

但是,这仅在值完全匹配时才有效.我需要做喜欢"过滤.我使用 __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.

推荐答案

您走对了!

您要做的第一件事是使用getattr 访问属性,而不是__dict__getattr 将始终做正确的事情,即使(对于更复杂的模型可能是这种情况)映射的属性不是列属性.

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.

另一个缺失的部分是您可以多次指定 filter(),只需用该方法调用的结果替换旧的查询对象.所以基本上:

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

这篇关于SQLAlchemy - 从 dict 动态构建查询过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆