python - sqlalchemy 不是 NULL 选择

标签 python sqlalchemy

如何像在 SQL 中一样添加过滤器以从特定列中选择不为 NULL 的值?

SELECT * 
FROM table 
WHERE YourColumn IS NOT NULL;

我怎样才能对 SQLAlchemy 过滤器做同样的事情?

select = select(table).select_from(table).where(all_filters) 

最佳答案

column_obj != None 将产生 IS NOT NULL constraint :

In a column context, produces the clause a != b. If the target is None, produces a IS NOT NULL.

或使用 is_not() *:

Implement the IS NOT operator.

Normally, IS NOT is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS NOT may be desirable if comparing to boolean values on certain platforms.

演示:

>>> from sqlalchemy.sql import column
>>> column('YourColumn') != None
<sqlalchemy.sql.elements.BinaryExpression object at 0x10f81aa90>
>>> print(column('YourColumn') != None)
"YourColumn" IS NOT NULL
>>> column('YourColumn').is_not(None)
<sqlalchemy.sql.elements.BinaryExpression object at 0x11081edf0>
>>> print(column('YourColumn').is_not(None))
"YourColumn" IS NOT NULL

你不能在这里使用 is not None,因为 is not object identity inequality test不能像 != 那样被重载;你只会得到 True 而不是 ColumnClause 实例与 None 单例不是同一个对象:

>>> column('YourColumn') is not None
True

*) 该方法以前被命名为 isnot(),并在 SQLAlchemy 1.4 中重命名。旧名称仍可用于向后兼容。

关于python - sqlalchemy 不是 NULL 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21784851/

相关文章:

python - Keras Transfer Learning Resnet50 using fit_generator got high acc but low val_acc 问题

python - 奇怪的 python 文字索引 : ['False' , 'True' ][条件]

python - Python 中的凯撒密码函数

python - SQLAlchemy 急切加载多个关系

python - Google Cloud SQL - 我可以使用 SQLAlchemy 直接访问数据库吗 - 不在本地

python - 在 SQLAlchemy 中使用字典/数据帧值执行更新

python - 模块可以有属性吗?

python - 从具有特定列和条件的数据框中选择行(不使用列名)

python - sqlalchemy 中的三元组距离操作

python - SQLAlchemy - 多个类,相同的表