所以我有一个这样的模型:
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
这适用于
border
作为 JSON null
和 PostgresQL NULL
:
from sqlalchemy.sql.expression import text
filter(myModel.border != text("'null'"))
(用
SQLAlchemy==1.1.14
测试)
从 sqlalchemy>=0.7.9 开始,您可以使用过滤运算符
.isnot
而不是比较这样的约束 - filter(myModel.border.isnot(None))
要获取具有空边框的模型,请执行
filter(myModel.border.is_(None))
PostgreSQL 有函数 jsonb_typeof,它返回 json 值的字符串类型。因此,您可以将空值过滤为
jsonb_typeof(myModel.border) != 'null'
。
您可以在 PostgreSQL 文档中找到详细信息
从 sqlalchemy 导入 null
#如果你尝试在数据库中插入数据:YourModel(my_json_column = null())
#通过过滤器获取数据:select(Table).where(Table.my_json_column.is_(None))
您将能够使用值 null() 来持久化它
>>> from sqlalchemy import null
>>> filter(myModel.border != null())