How do 'primaryjoin' and 'secondaryjoin' work for many-to-many relationship in SQLAlchemy? How do 'primaryjoin' and 'secondaryjoin' work for many-to-many relationship in SQLAlchemy? flask flask

How do 'primaryjoin' and 'secondaryjoin' work for many-to-many relationship in SQLAlchemy?


  1. In a many to many relationship, the primaryjoin expression describes the join between the left table and the junction table, and the secondaryjoin describes the join between the junction table and the right table. In other words, the primaryjoin expression is saying, "find all rows in the followers table where follower_id is X", the secondaryjoin expression is saying "find all rows in the followers table where followed_id is X", and get those two together to find all users that follow user X, and all users that are followed by user X.

  2. It depends on the direction you're querying from. When you ask for user.followers, it will find them by using the primaryjoin to query the followers table for all rows where followed_id == user.id, and retrieve the user other with other.id == follower_id. When you ask for user.followed, it uses the secondaryjoin to query the followers table for all rows where follower_id == user.id, and retrieve the user other with other.id == followed_id.

  3. Because you're adding it to self.followed collection, telling SQLAlchemy that's someone self is following. If you were adding it to the self.followers collection, you'd be doing the inverse, telling SQLAlchemy that 'user' is a follower of self.

Reference: SQLAlchemy documentation for specifying alternative join conditions (primaryjoin and secondaryjoin).