问题:sqlalchemy不为空选择

如何像在SQL中一样添加过滤器,以从特定列中选择非空值?

SELECT * 
FROM table 
WHERE YourColumn IS NOT NULL;

如何使用SQLAlchemy过滤器执行相同操作?

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

How can I add the filter as in SQL to select values that are NOT NULL from a certain column ?

SELECT * 
FROM table 
WHERE YourColumn IS NOT NULL;

How can I do the same with SQLAlchemy filters?

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

回答 0

column_obj != None会产生一个IS NOT NULL约束

在列上下文中,产生子句a != b。如果目标是None,则生成一个IS NOT NULL

或使用isnot()(0.7.9中的新功能):

实施IS NOT操作员。

通常,IS NOT当与的值进行比较时,会自动生成None,解析为NULL。但是,IS NOT如果与某些平台上的布尔值进行比较,则可能需要显式使用。

演示:

>>> from sqlalchemy.sql import column
>>> column('YourColumn') != None
<sqlalchemy.sql.elements.BinaryExpression object at 0x10c8d8b90>
>>> str(column('YourColumn') != None)
'"YourColumn" IS NOT NULL'
>>> column('YourColumn').isnot(None)
<sqlalchemy.sql.elements.BinaryExpression object at 0x104603850>
>>> str(column('YourColumn').isnot(None))
'"YourColumn" IS NOT NULL'

column_obj != None will produce a IS NOT NULL constraint:

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

or use isnot() (new in 0.7.9):

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.

Demo:

>>> from sqlalchemy.sql import column
>>> column('YourColumn') != None
<sqlalchemy.sql.elements.BinaryExpression object at 0x10c8d8b90>
>>> str(column('YourColumn') != None)
'"YourColumn" IS NOT NULL'
>>> column('YourColumn').isnot(None)
<sqlalchemy.sql.elements.BinaryExpression object at 0x104603850>
>>> str(column('YourColumn').isnot(None))
'"YourColumn" IS NOT NULL'

回答 1

从0.7.9版本开始,您可以使用filter运算符.isnot而不是比较约束,如下所示:

query.filter(User.name.isnot(None))

仅当担心pep8时才需要此方法。

来源:sqlalchemy文档

Starting in version 0.7.9 you can use the filter operator .isnot instead of comparing constraints, like this:

query.filter(User.name.isnot(None))

This method is only necessary if pep8 is a concern.

source: sqlalchemy documentation


回答 2

如果其他人想知道,可以使用is_生成foo IS NULL

>>>来自sqlalchemy.sql导入列
>>>打印列('foo')。is_(无)
foo IS NULL
>>>打印列('foo')。isnot(无)
foo不为空

In case anyone else is wondering, you can use is_ to generate foo IS NULL:

>>> from sqlalchemy.sql import column
>>> print column('foo').is_(None)
foo IS NULL
>>> print column('foo').isnot(None)
foo IS NOT NULL

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。