小编cro*_*ind的帖子

SQLAlchemy:过滤存储在 JSONB 字段的嵌套列表中的值

假设我有一个名为 的模型Item,其中包含一个 JSONB 字段data。其中一条记录存储了以下 JSON 对象:

{
    "name": "hello",
    "nested_object": {
        "nested_name": "nested"
    },
    "nested_list": [
        {
            "nested_key": "one"
        },
        {
            "nested_key": "two"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我可以通过对name字段进行过滤来找到此记录:

Session().query(Item).filter(Item.data["name"] == "hello")
Run Code Online (Sandbox Code Playgroud)

我可以通过同样过滤嵌套对象来找到此记录:

Session().query(Item).filter(Item.data[("nested_object","nested_name")] == "hello")
Run Code Online (Sandbox Code Playgroud)

但是,我正在努力通过过滤存储在嵌套列表中的项目的值来寻找找到此记录的方法。换句话说,如果用户提供了值“一”,我想找到上面的记录,并且我知道要nested_keynested_list.

是否可以使用可用的 SQLAlchemy 过滤器来实现这一点?

python postgresql json sqlalchemy

5
推荐指数
1
解决办法
4635
查看次数

标签 统计

json ×1

postgresql ×1

python ×1

sqlalchemy ×1