简体   繁体   中英

How to find nested value in postgres JSONB using sqlalchemy?

I have a postgres table with JSONB column name entity . The example of json structure is:

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

I need to find records by 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.

Update : My model is made dynamic, because multiple tables are using same structure just the different table name. 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:

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. The Operator @> is contains() in SQLAlchemy for JSONB columns

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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