简体   繁体   English

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

[英]How to find nested value in postgres JSONB using sqlalchemy?

I have a postgres table with JSONB column name entity .我有一个带有 JSONB 列名entity的 postgres 表。 The example of json structure is: json结构示例为:

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

I need to find records by name_value .我需要按name_value查找记录。 I can get it by using query:我可以通过使用查询得到它:

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

The problem is: I cannot find the way to create that same query using sqlalchemy ORM.问题是:我找不到使用 sqlalchemy ORM 创建相同查询的方法。

Update : My model is made dynamic, because multiple tables are using same structure just the different table name.更新:我的 model 是动态的,因为多个表使用相同的结构,只是表名不同。 Here is the code:这是代码:

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

And then I use 3 functions to initiate my Models and get one I currently need:然后我使用 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)

You can use the following SQLAlchemy expression.您可以使用以下 SQLAlchemy 表达式。 The Operator @> is contains() in SQLAlchemy for JSONB columns运算符 @> 是 JSONB 列的 SQLAlchemy 中的 contains()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM