我的 postgres 数据库表“blocks”中有一个名为“randomblocks”的 jsonb 列,其数据与 json 类似:
{
"block": {
"1": {
"color": [
"black",
"white"
]
},
"2": {
"color": [
"grey",
"silver"
]
}
}
}
如果我想删除“block”>“2”,根据postgresdocumentation的查询将类似于:
UPDATE blocks SET randomblocks = randomblocks #- '{block,2}' where blockid=1;
目前我陷入了原始查询的困境,这不是实现此目的的优雅方法:
stmt = text("UPDATE blocks SET randomblocks = randomblocks #- '{block, :x}' where blockid= :y")
stmt = stmt.bindparams(x=2, y=1)
db.session.execute(stmt)
如何使用 sqlalchemy 编写相同的查询而不使用原始查询,如果可能的话最好使用 orm 方式?
您应该能够使用
delete_path
path = array("block", "2")
stmt = (
update(Block)
.values(
{
Block.randomblocks: Block.randomblocks.delete_path(path)
}
)
.where(...)
)