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

时间:2021-04-26 21:18:52

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:

所以我有一个从网页传递的字典。我想基于dict动态构建查询。我知道我能做到:

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.

不知道如何从那里构建查询。任何帮助都是极好的。

1 个解决方案

#1


43  

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.

你要做的第一件事就是使用getattr访问属性,而不是__dict__; 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. So basically:

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

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

#1


43  

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.

你要做的第一件事就是使用getattr访问属性,而不是__dict__; 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. So basically:

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

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