在 SQLAlchemy 中按空值过滤 postgres JSON 列

问题描述 投票:0回答:6

所以我有一个这样的模型:

class myModel(Base):

    id = Column(Integer, primary_key=True)
    border = Column(JSONB)

如何查询没有边框的行?我试过:

filter(myModel.border != None) #nope
filter(myModel.border != 'null') #nope
from sqlalchemy import null
filter(myModel.border != null()) #nope

该值显然作为

“JSON 编码的空值”
存储在 postgres 中。当实例化时,它肯定会序列化回 python
None
,但我不知道如何查询它。看起来你可以在列上设置
none_as_null
,即:

Column(JSONB(none_as_null=True))

它将 JSON 编码的

null
替换为 SQL null,但这似乎很奇怪,必须对所有列执行此操作。我在这里缺少什么?

编辑:应该提到这是 sqlalchemy 的 v0.9.8

python postgresql sqlalchemy
6个回答
4
投票

这适用于

border
作为 JSON
null
和 PostgresQL
NULL
:

from sqlalchemy.sql.expression import text
filter(myModel.border != text("'null'"))

(用

SQLAlchemy==1.1.14
测试)


4
投票

从 sqlalchemy>=0.7.9 开始,您可以使用过滤运算符

.isnot
而不是比较这样的约束 -
filter(myModel.border.isnot(None))

要获取具有空边框的模型,请执行

filter(myModel.border.is_(None))


3
投票

PostgreSQL 有函数 jsonb_typeof,它返回 json 值的字符串类型。因此,您可以将空值过滤为

jsonb_typeof(myModel.border) != 'null'
。 您可以在 PostgreSQL 文档

中找到详细信息

0
投票

使用

JSON.NULL
。来自文档

要插入或选择 SQL NULL 值,请使用常量

null()
:

from sqlalchemy import null
conn.execute(table.insert(), json_value=null())

要插入或选择 JSON 值

"null"
,请使用常量
JSON.NULL
:

conn.execute(table.insert(), json_value=JSON.NULL)

所以就你而言,

from sqlalchemy import JSON

myModel.query.filter(myModel.border != JSON.NULL)

0
投票

从 sqlalchemy 导入 null

#如果你尝试在数据库中插入数据:YourModel(my_json_column = null())

#通过过滤器获取数据:select(Table).where(Table.my_json_column.is_(None))


-2
投票

您将能够使用值 null() 来持久化它

>>> from sqlalchemy import null

>>> filter(myModel.border != null()) 
© www.soinside.com 2019 - 2024. All rights reserved.