You need to enable JavaScript to run this app. 如何使用SQLAlchemy ORM查询PostgreSQL JSONB列的嵌套值
优惠活动
大模型
产品
解决方案
定价
更多

如何使用SQLAlchemy ORM查询PostgreSQL JSONB列的嵌套值

场景说明
  • 业务使用PostgreSQL数据库,存储表中包含类型为JSONB的entity列,列存储的JSON结构示例:
{
  "some_key": "some value",
  "properties": {
    "name": ["name_value"]
  }
}
  • 需求为按name数组内的name_value值匹配查询记录,已验证可通过原生SQL命中目标结果:
SELECT entity FROM my_table WHERE entity->'properties' @> '{"name": ["name_value"]}';
  • 当前卡点:尚未找到SQLAlchemy ORM层面的等价实现方式;同时因业务存在大量表结构完全一致、仅表名不同的表,现有代码采用动态生成SQLAlchemy模型的方式适配多表查询需求。
现有动态模型实现代码
  • 动态模型生成核心逻辑:
...
Base = declarative_base(engine)

class ForeignBase(AbstractConcreteBase, Base):
    pass

def make_model(name):
    class Entity(ForeignBase):
        __tablename__ = name
        __mapper_args__ = {"polymorphic_identity": name, "concrete": True}
        __table_args__ = {"extend_existing": True}

        id = Column(String, primary_key=True)
        entity = Column(JSONB, nullable=True)
        ...
    configure_mappers()
    return Entity
  • 动态模型配套工具函数:
def get_model_list():
    tables_names_list = get_table_name_list()
    model_list = [make_model(PREFIX + table_name) for table_name in tables_names_list]
    return model_list

def get_tables_dict():
    return {table.__tablename__: table for table in ForeignBase.__subclasses__()}

def get_table_object(table_name):
    return get_tables_dict().get(table_name)
ORM等价实现方案

SQLAlchemy对PostgreSQL JSONB的包含查询操作有原生支持,无需手写原生SQL即可实现完全等价的逻辑,且完全兼容现有动态模型的实现方式。
具体实现步骤:

  1. 通过现有工具函数获取目标表对应的动态模型对象:
    # 以查询my_table表为例
    TargetModel = get_table_object("my_table")
    
  2. 构造匹配条件:对entity列下的properties节点调用contains方法,传入匹配的JSON规则:
    # 该逻辑会自动映射为PostgreSQL的 @> 包含操作符,和原生SQL逻辑完全一致
    match_filter = TargetModel.entity["properties"].contains({"name": ["name_value"]})
    
  3. 执行查询获取结果:
    session.query(TargetModel.entity).filter(match_filter).all()
    

实现注意点:

  • 生成的SQL语句和手动验证的原生语句完全等价,无查询逻辑偏差。
  • 该写法不需要对现有动态模型生成逻辑、工具函数做任何改动,可直接复用现有代码。
  • 匹配的name_value可直接替换为程序变量传入,SQLAlchemy会自动完成参数转义,避免SQL注入风险,无需手动拼接JSON字符串。

内容的提问来源于stack exchange,提问作者SarunasCard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.24 11:36:03