SQLAlchemy 核心选择其中条件包含布尔表达式`is False` [英] SQLAlchemy Core select where condition contains boolean expression `is False`

查看:21
本文介绍了SQLAlchemy 核心选择其中条件包含布尔表达式`is False`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 SQLAlchemy 表达式语言选择带有 where 条件的列来检查布尔表达式.例子:

How to use SQLAlchemy expression language to select columns with where condition to check boolean expression. example:

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

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

This doesn't give syntax error, but evaluates the condition wrong. I cannot use == False which gives error. SQLAlchemy Core v.1.0.8

推荐答案

身份比较运算符 is 在 Python 中不能重载,所以

The identity comparison operator is cannot be overloaded in Python, so

table.c.is_num is False

比较 Column 对象和 False 的身份,由于它们显然不是同一个对象,因此计算结果为 False.作者

compares the identities of the Column object and False, and since they're clearly not the same object, evaluates to False. By

我不能使用 == False 这会导致错误

I cannot use == False which gives error

您可能的意思是,某些遵循 PEP-8 的 Python linter 给出了你一个警告.根据 True 或 False 检查相等性仍然是有效的 Python,尽管 unpythonic 在一般意义 - 但它在 SQLAlchemy 过滤器中确实有意义它是在文档中使用.例如:

you probably mean that some Python linter adhering to PEP-8 gives you a warning. Checking equality against True or False is still valid Python, though unpythonic in the general sense – but it does make sense in SQLAlchemy filters and it is used in the docs. For example:

In [5]: t.c.bar == False
Out[5]: <sqlalchemy.sql.elements.BinaryExpression object at 0x7fdc355a1da0>

In [6]: print(_)
foo.bar = false

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

But: instead of comparing a boolean to a boolean you could use the value itself:

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_().一些后端可能不支持布尔类型,但 SQLAlchemy 处理转换:

since SQLAlchemy ColumnOperators overload the __invert__ to not_(). Some backends may not support a boolean type, but SQLAlchemy handles the conversion:

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

这篇关于SQLAlchemy 核心选择其中条件包含布尔表达式`is False`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆