Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: eager loading of more than one relationship

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)?

like image 366
Michael Ekoka Avatar asked Oct 06 '15 22:10

Michael Ekoka


People also ask

How do you create a many to many relationship in SQLAlchemy?

Many to Many relationship between two tables is achieved by adding an association table such that it has two foreign keys - one from each table's primary key.

What is lazy loading in SQLAlchemy?

The loading of relationships falls into three categories; lazy loading, eager loading, and no loading. Lazy loading refers to objects are returned from a query without the related objects loaded at first.

What is Joinedload?

This option, known as joinedload() , connects a JOIN (by default a LEFT OUTER join) to the statement and populates the scalar/collection from the same result set as that of the parent: sql>>> jack = session. query(User).\ ... options(joinedload('addresses')).\ ...

What is Backref in SQLAlchemy?

The sqlalchemy backref is one of the type keywords and it passed as the separate argument parameters which has to be used in the ORM mapping objects. It mainly includes the event listener on the configuration attributes with both directions of the user datas through explicitly handling the database relationships.


1 Answers

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))
)
like image 115
van Avatar answered Oct 23 '22 07:10

van