如何像在 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 isNone
, produces aIS NOT NULL
.
或使用 is_not()
*:
Implement the
IS NOT
operator.Normally,
IS NOT
is generated automatically when comparing to a value ofNone
, which resolves toNULL
. However, explicit usage ofIS 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/