Select NULL Values in SQLAlchemy

前端 未结 3 1698
遥遥无期
遥遥无期 2020-12-05 16:54

Here\'s my (PostgreSQL) table --

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

test=>          


        
相关标签:
3条回答
  • 2020-12-05 17:24

    Since SQLAlchemy 0.7.9 you may use the is_ method of the column.

    A filter expression like:

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

    will generate the parameterized SQL:

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

    0 讨论(0)
  • 2020-12-05 17:27

    i ran into a similar problem

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

    short answer: - there is not a column operator for IS (NOT) NULL now, but there will be

    in the meantime you can use either:

    filter(tablename.is_deleted.op("IS NOT")(True))

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

    0 讨论(0)
  • 2020-12-05 17:33

    (as indicated by @augurar): Because sqlalchemy uses magic methods (operator overloading) to create SQL constructs, it can only handle operator such as != or ==, but is not able to work with is (which is a very valid Python construct).

    Therefore, to make it work with sqlalchemy, you should use:

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

    , basically replace the is None with == None. In this case your query will be translated properly to the following 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 != ?
    

    See IS NULL in the documentation.

    0 讨论(0)
提交回复
热议问题