Python sqlalchemy 不是 NULL 选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21784851/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sqlalchemy IS NOT NULL select
提问by salamey
How can I add the filter as in SQL to select values that are NOT NULL from a certain column ?
如何在 SQL 中添加过滤器以从特定列中选择非 NULL 的值?
SELECT * 
FROM table 
WHERE YourColumn IS NOT NULL;
How can I do the same with SQLAlchemy filters?
如何使用 SQLAlchemy 过滤器做同样的事情?
select = select(table).select_from(table).where(all_filters) 
采纳答案by Martijn Pieters
column_obj != Nonewill produce a IS NOT NULLconstraint:
column_obj != None会产生一个IS NOT NULL约束:
In a column context, produces the clause
a != b. If the target isNone, produces aIS NOT NULL.
在列上下文中,生成子句
a != b。如果目标是None,则生成一个IS NOT NULL。
or use isnot()(new in 0.7.9):
或使用isnot()(0.7.9 中的新功能):
Implement the
IS NOToperator.Normally,
IS NOTis generated automatically when comparing to a value ofNone, which resolves toNULL. However, explicit usage ofIS NOTmay be desirable if comparing to boolean values on certain platforms.
实现
IS NOT运算符。通常,
IS NOT在与 的值比较时自动生成,该值None解析为NULL。但是,IS NOT如果与某些平台上的布尔值进行比较,则可能需要显式使用。
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'
回答by Filipe Spindola
Starting in version 0.7.9 you can use the filter operator .isnotinstead of comparing constraints, like this:
从 0.7.9 版本开始,您可以使用过滤器运算符.isnot而不是比较约束,如下所示:
query.filter(User.name.isnot(None))
query.filter(User.name.isnot(None))
This method is only necessary if pep8 is a concern.
只有在考虑 pep8 时才需要此方法。
source: sqlalchemy documentation
回答by Matthew Moisen
In case anyone else is wondering, you can use is_to generate foo IS NULL:
如果其他人想知道,您可以使用is_来生成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

