[英]flask-sqlalchemy filter using text array
我正在尝试通过字符串过滤我的flask-sqlalchemy查询。 我创建字符串的过程将导致以下数组:
["user.name == 'Sid'", "user.role == 'admin'"]
它由以下内容组成:
for i in myarray:
filter_string = "%s.%s == '%s'" % (self.model.__tablename__, i[0], i[2])
or_filters.append(filter_string)
这是我的使用方式:
db = SQLAlchemy(app)
...
class myclass:
def __init(self, model):
self.model = model
self.q = db.session.query(self.model)
def get(self, cfg):
...
# the following line works
myfilter = [User.name == 'Sid', User.role == 'admin']
# the following line does not work, but I need it to. How to modify into the line above?
myfilter = ["user.name == 'Sid'", "user.role == 'admin'"]
if myfilter is not None:
self.q = self.apply_filter(myfilter)
items = self.q.all()
return items
def apply_filter(self, ftr):
self.q.filter(or_(*ftr))
Ilja有一个很好的解决方案
myfilter = getattr(self.model, i[0]).is_(i[2])
if myfilter is not None:
self.q = self.apply_filter(myfilter)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.