如何使用postgres上的SQLAlchemy将元素插入嵌套的JSONB数组

2024-06-09 13:54:15 发布

您现在位置:Python中文网/ 问答频道 /正文

关于如何在postgres中存储JSONB,我已经看到了各种各样的好答案,但是从postgres9.5开始,我们现在可以插入到现有的JSONB数组中,而无需更新列中的数据。我所能找到的资料中没有任何地方记录了这一点,而且由于我是SQLAlchemy的新手(在某种程度上也是python的新手),阅读这些代码对我的帮助并没有我想要的那么大。你知道吗

我正在使用postgres10.9、python3.7和SQLAlchemy 1.3.8(带有GINO包装器)

这只是最近的一次尝试,但也有许多尝试出现了无数不同的错误:

await gathering. \
        update(participation=func.jsonb_insert("participation",
                                                "{applications}",
                                                func.to_jsonb(json.dumps(application)))). \
        apply()

参与列中,我有一个JSONB对象

{ 
    "applications": [ { ... element to be appended} ] 
}

在这种特殊情况下,代码会产生一个错误:

could not determine polymorphic type because input has type unknown


Tags: to数据答案代码sqlalchemytype错误postgres
1条回答
网友
1楼 · 发布于 2024-06-09 13:54:15

我想出来了。。你知道吗

ajs = json.dumps(application)
await gathering. \
                update(participation=func.jsonb_insert(
                       json.dumps(gathering.participation), 
                       ["applications","0"],  ajs)). \
                apply()

为试错干杯。有一个比这个更优雅的解决方案。你知道吗

相关问题 更多 >