初心者のメモ

Python enthusiast

SQLAlchemy - 複数テーブルを横断してロードする方法

親テーブル - 子テーブル - 孫テーブル のようなrelationのデータベースがあるとして、

# models_generated.py
class Parent(Base):
    __tablename__ = 'parent'

    id = Column(Integer, primary_key=True)
    ..略..

    child = relationship('Child')


class Child(Base):
    __tablename__ = 'child'

    id = Column(Integer, primary_key=True)
    ..略..

    grandson = relationship('Grandson')


class Grandson(Base):
    __tablename__ = 'grandson'

    id = Column(Integer, primary_key=True)
    ..略..

親テーブルを子・孫テーブルのデータと一緒にロードする方法は次のとおり。

ses = init_session()
parent_models = ses.query(Parent).options(joinedload(Parent.child).joinedload(Child.grandson))