如何使用 sqlalchemy 在 postgres JSONB 中查找嵌套值?

时间:2021-04-21 05:55:40

标签: python postgresql sqlalchemy

我有一个带有 JSONB 列名 entity 的 postgres 表。 json结构示例为:

{
  "some_key": "some value",
  "properties": {
    "name": ["name_value"],
  }
}

我需要按 name_value 查找记录。我可以通过使用查询来获取它:

SELECT entity FROM my_table where entity->'properties' @> {"name": ["name_value"]};

问题是:我找不到使用 sqlalchemy ORM 创建相同查询的方法。

更新: 我的模型是动态的,因为多个表使用相同的结构,只是表名不同。代码如下:

...
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

然后我使用 3 个函数来启动我的模型并获得我当前需要的一个:

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)

1 个答案:

答案 0 :(得分:0)

您可以使用以下 SQLAlchemy 表达式。运算符@> 是 JSONB 列的 SQLAlchemy 中的 contains()

Session().query(MyTable).filter(MyTable.entity["properties"].contains({"name": ["name_value"]})).with_entities(MyTable.entity).all()
相关问题