Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy : eager loading relationships of relationships of relationship

I have this structure:

class User(DeclarativeBase):
   ...
   teamMemberships = orm.relationship("TeamXREF",backref="user",lazy = "dynamic")


class TeamXREF(DeclarativeBase):
   ...


class Team(DeclarativeBase):
   ...
   name=db.Column(String)
   teamMembers = orm.relationship("TeamXREF",backref="team",lazy = "dynamic")

However, I can't manage to write in 1 query (I always end up with loops and multiple queries) that eager loads all these info at once:

  • user.teamMemberships
  • user.teamMemberships.team
  • user.teamMemberships.team.teamMembers
  • user.teamMemberships.team.teamMembers.user
like image 254
ptou Avatar asked May 02 '15 15:05

ptou


People also ask

What is Joinedload?

joined loading - available via lazy='joined' or the joinedload() option, this form of loading applies a JOIN to the given SELECT statement so that related rows are loaded in the same result set.

What does SQLAlchemy relationship do?

The relationship function is a part of Relationship API of SQLAlchemy ORM package. It provides a relationship between two mapped classes. This corresponds to a parent-child or associative table relationship.

What is Backref in SQLAlchemy?

In Flask-SQLAlchemy, the backref parameter in relationship method allows you to declare a new property under a specified class as seen in the example in their docs: class Person(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) addresses = db.relationship('Address', backref='person ...

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

The comments class attribute defines a One-to-Many relationship between the Post model and the Comment model. You use the db. relationship() method, passing it the name of the comments model ( Comment in this case). You use the backref parameter to add a back reference that behaves like a column to the Comment model.


1 Answers

You might try just explicitly loading the items in the query rather than hard coding it into your relationships. Something like this:

from sqlalchemy.orm import joinedload
Session.query(User).options(joinedload('teamMemberships').joinedload('team').joinedload('teamMembers').joinedload('user'))

http://docs.sqlalchemy.org/en/improve_toc/orm/loading_relationships.html#loading-along-paths

like image 114
Ian Wilson Avatar answered Oct 01 '22 23:10

Ian Wilson