Skip to main content
 首页 » 编程设计

python之SQLAlchemy 核心选择条件包含 bool 表达式 `is False`

2025年05月04日15sky-heaven

如何使用 SQLAlchemy 表达式语言选择具有 where 条件的列来检查 bool 表达式。示例:

select([table]).\ 
    where(and_(table.c.col1 == 'abc', 
               table.c.is_num is False  
    )) 

这不会给出语法错误,但会错误地评估条件。我不能使用 == False 这会产生错误。 SQLAlchemy 核心 v.1.0.8

请您参考如下方法:

identity comparison operator is不能在 Python 中重载,所以

table.c.is_num is False 

比较 Column 对象和 False 的标识,由于它们显然不是同一个对象,因此计算结果为 False。通过

I cannot use == False which gives error

你可能是说一些 Python linter 遵循 PEP-8给你一个警告。尽管 unpythonic,检查 True 或 False 的相等性仍然是有效的 Python在一般意义上——但它does make sense in SQLAlchemy filters它是used in the docs .例如:

In [5]: t.c.bar == False 
Out[5]: <sqlalchemy.sql.elements.BinaryExpression object at 0x7fdc355a1da0> 
 
In [6]: print(_) 
foo.bar = false 

但是:您可以使用值本身,而不是将 bool 值与 bool 值进行比较:

select([table]).\ 
    where(and_(table.c.col1 == 'abc', 
               ~table.c.is_num 
    )) 

这将转化为(大约):

SELECT ... FROM table WHERE col1 = 'abc' AND NOT is_num 

自从 SQLAlchemy ColumnOperators重载__invert__至 not_() .某些后端可能不支持 bool 类型,但 SQLAlchemy 会处理转换:

In [6]: print((~t.c.bar).compile(dialect=sqlite.dialect())) 
foo.bar = 0