如何在sqlalchemy中使用jsonb - 和#-进行删除

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

我的 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 方式?

python postgresql sqlalchemy jsonb
1个回答
0
投票

您应该能够使用

delete_path

path = array("block", "2")
stmt = (
    update(Block)
    .values(
        {
            Block.randomblocks: Block.randomblocks.delete_path(path)
        }            
    )
    .where(...)
)

https://docs.sqlalchemy.org/en/20/dialects/postgresql.html#sqlalchemy.dialects.postgresql.JSONB.Comparator.delete_path

© www.soinside.com 2019 - 2024. All rights reserved.