在SQLAlchemy中选择NULL值

时间:2011-04-09 04:40:42

标签: python sql database sqlalchemy

这是我的(PostgreSQL)表 -

test=> create table people (name varchar primary key,
                            marriage_status varchar) ; 

test=> insert into people values ('Ken', 'married');
test=> insert into people values ('May', 'single');
test=> insert into people values ('Joe', NULL);

我想选择已知结婚的所有人,即包括那些有NULL_status的人。

工作 -

test=> select * from people where marriage_status != 'married' ; 
 name | marriage_status 
------+-----------------
 May  | single
(1 row)

当然这样做 -

test=> select * from people where marriage_status != 'married'
       or marriage_status is NULL ; 
 name | marriage_status 
------+-----------------
 May  | single
 Joe  | 

问题是我正在使用 -

从SQLAlchemy访问它
...filter(or_(people.marriage_status!='married',
              people.marriage_status is None))

被翻译成 -

SELECT people.name as name,
       people.marriage_status as marriage_status
FROM people 
WHERE people.marriage_status != %(status_1)s OR False
sqlalchemy.engine.base.Engine.... {'status_1': 'married'}

工作 -

test=> select * from people where marriage_status != 'married'
       or False; 
 name | marriage_status 
------+-----------------
 May  | single
(1 row)

也没有 -

test=> select * from people where marriage_status != 'married'
       or NULL; 
 name | marriage_status 
------+-----------------
 May  | single
(1 row)

如何通过SQLAlchemy选择NULL值?

3 个答案:

答案 0 :(得分:86)

(由@augurar表示):因为 sqlalchemy 使用魔术方法(运算符重载)来创建SQL构造,所以它只能处理运算符,例如!===,但无法使用is(这是一个非常有效的Python构造)。

因此,要使其与sqlalchemy一起使用,您应该使用:

...filter(or_(people.marriage_status!='married', people.marriage_status == None))

,基本上将is None替换为== None。在这种情况下,您的查询将正确转换为以下SQL:

SELECT people.name AS people_name, people.marriage_status AS people_marriage_status 
FROM people 
WHERE people.marriage_status IS NULL OR people.marriage_status != ?

请参阅documentation中的IS NULL

答案 1 :(得分:27)

自SQLAlchemy 0.7.9起,您可以使用该列的is_方法。

过滤器表达式如:

filter(or_(people.marriage_status!='married', people.marriage_status.is_(None)))

将生成参数化SQL:

WHERE people.marriage_status != %(status_1)s OR people.marriage_status IS NULL

答案 2 :(得分:0)

我遇到了类似的问题

https://groups.google.com/forum/?fromgroups#!topic/sqlalchemy/EVpxsNp5Ifg%5B1-25%5D

简短回答:   - 现在没有IS(NOT)NULL的列运算符,但是会有

同时你可以使用:

filter(tablename.is_deleted.op(“IS NOT”)(True))

filter(coalesce(tablename.is_deleted,False)!= True)