python - bool 类型列作为 SQLAlchemy 中的 ClauseElement

标签 python sqlalchemy

为什么在 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/

相关文章:

python - 关于 python ctypes 中调整大小的问题

python - 在 Python 中生成随机 UTF-8 字符串

python - 如何为 Linux 和 Windows 分发带有嵌入式 Firebird SQL 的 Python 程序

python - 当我没有表对象时,如何在 SQLAlchemy 中删除表?

insert - SQLAlchemy 原始 sql 与表达式语言语句

python - __table_args__ 的 Sqlalchemy 声明式继承

python - 值错误 :could not convert string to float: b'*********'

python - 当前实现中如何避免索引超出范围错误?

Python 存储数据

python - sqlalchemy:空比较交换性