-->

SQLAlchemy: eager loading of more than one relatio

2020-02-27 11:21发布

问题:

I want to query this structure:

A -> B
B -> C
B -> D

what's the syntax to do this with the Load interface, the documentation is not very clear on this (http://docs.sqlalchemy.org/en/latest/orm/loading_relationships.html#sqlalchemy.orm.joinedload). All I see is how to do:

A -> B
B -> C
C -> D

Given the query:

query(A).options(joinedload(A.b).joinedload(B.c))

How do I go backward in the chain to specify the second relationship on B (B.d)?

回答1:

Just add another .options(...) with a new relationship path:

q = (
    session
    .query(A)
    .options(joinedload(A.b).joinedload(B.c))
    .options(joinedload(A.b).joinedload(B.d))
)