我有这个模型:
class PUC(Base):
pucId = Column(Integer, primary_key=True)
asset = Column(TINYINT)
article = Column(TINYINT)
more values ...
more values ...
而且我需要动态地执行查询(我尝试过这种方式):
pucs = session.query(PUC).filter(PUC[unique_by_param] == 1).all()
unique_by_param
的值来自前端。unique_by_param
的示例是:{str}'asset'
,{str}'article'
,{str}'another_model_value'
我真正需要的是一种方法。
session.query(PUC).filter(PUC.asset == 1)
或session.query(PUC).filter(PUC.article == 1)
动态地,就像我尝试的第一种方法一样。使用(
PUC[unique_by_param]
)的结果是TypeError: 'DeclarativeMeta' object is not subscriptable
我以前曾经使用过一种方法,但是执行起来不是很好,但是执行起来却不是很好:
# this is a accounting table, so this have around 250 columns
#and this special columns be around 70 variables...
#So this isn't an option o do this.
if unique_by_param == 'asset':
q = (PUC.asset == 1)
elif unique_by_param == 'article':
q = (PUC.article)
elif ...more values:
pucs = session.query(PUC).filter(or_(*q))
最佳答案
这是使用filter_by
和keyword argument unpacking的方法:
keyword = {unique_by_param : 1}
session.query(PUC).filter_by(**keyword).all()
关于python - 我可以对SQLAlchemy进行动态比较吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38838939/