为什么在 SQLAlchemy 中不能将 Boolean 类型的列本身用作 ClauseElement?
session.query(Table).filter(Table.name == 'huszar', Table.valid)
当然 Table.valid == True
可以工作,但对我来说看起来有点丑...
最佳答案
我想也许您使用的是 0.7,而 ORM 还不支持在单个 filter() 调用中使用多个条件,这是在 0.8 中添加的,而且 0.7 似乎需要表绑定(bind)列(如果是独立的)。在 0.8 中一切正常:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
data = Column(String(20))
boolean = Column(Boolean)
# works
e = create_engine("sqlite://", echo=True)
# works
#e = create_engine("postgresql://scott:tiger@localhost/test", echo=True)
# works
#e = create_engine("mysql://scott:tiger@localhost/test", echo=True)
Base.metadata.create_all(e)
s = Session(e)
s.add_all([
A(data='a1', boolean=True),
A(data='a2', boolean=False),
A(data='a3', boolean=True),
])
# works
print s.query(A).filter(A.data > 'a1', A.boolean).all()
# works
print s.query(A).filter(A.boolean).all()
# if before 0.8, need to use and_() or table-bound column
# print s.query(A).filter(and_(A.data > 'a1', A.boolean)).all()
# print s.query(A).filter(A.__table__.c.boolean).all()
关于python - bool 类型列作为 SQLAlchemy 中的 ClauseElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15994938/