Python 我可以对SQLAlchemy进行动态比较吗?
我有这个模型:Python 我可以对SQLAlchemy进行动态比较吗?,python,sqlalchemy,Python,Sqlalchemy,我有这个模型: class PUC(Base): pucId = Column(Integer, primary_key=True) asset = Column(TINYINT) article = Column(TINYINT) more values ... more values ... 我需要动态地执行查询(我尝试了这种方式): unique\u by_param的值来自前端。 unique\u by_param的一个例子是:{str}'asset',{
class PUC(Base):
pucId = Column(Integer, primary_key=True)
asset = Column(TINYINT)
article = Column(TINYINT)
more values ...
more values ...
我需要动态地执行查询(我尝试了这种方式):
unique\u by_param
的值来自前端。
unique\u by_param
的一个例子是:{str}'asset'
,{str}'article'
,{str}'另一个模型值'
我真正需要的是一种方法。
session.query(PUC.asset==1)
或session.query(PUC.article==1)
动态过滤,就像我第一次尝试的那样
使用(PUC[unique\u by_param]
)的结果是TypeError:“DeclarativeMeta”对象不可订阅
有一种方法我以前用过,但不是很好的方法,但不是很好的方法:
# 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))
以下是一种使用
过滤方法的方法
如果PUC.asset
是TINYINT
,而不是bool
类型,那么您希望PUC.asset==True
做什么?是的,这是bool。因此,如果我检查了这个值,pucs
的值与@cricket\u 007No完全不同,你的列是一个TINYINT
,而不是BOOLEAN
值……这样就更好了@cricket\u 007`PUC.asset==1'@AdrianSerna你尝试的方法在某种程度上失败了吗?是的,这是一个很好的解决方案,但非常危险。我需要一种方法来动态但同时又安全。@AdrianSerna我想我应该删除它,因为这是一个很糟糕的建议。我相信第二个(更新的)答案更安全。
# 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))
keyword = {unique_by_param : 1}
session.query(PUC).filter_by(**keyword).all()