Indeed, your conclusion that you should use two relationship
s reflects that this is not only a good way to represent this connection, it is the only way
relationship
models not the remote table, Ride
in your case, but the connections between tables. There are two connections between Ride
and User
, for the two roles each user may play in a ride.
For more evidence of this fact, notice that you also have two relationship
's facing away from Ride
, toward User
, one for each branch of the connection. Since you have two of those, you would also require distinct backref's, one for each.
But, your code is not quite enough. You should tell sqlalchemy
that "this relationship is that one, only backwards". as it is, you have four relationships, none of whom know the existence of the other. This will manifest as mysterious effect of changes in Ride.driver
not reflected in User.rides_as_driver
.
The fix is easy, though, add a back_populates
to each relationship and sqlalchemy will keep them in sync:
class Ride:
driver = db.Relationship('User', primaryjoin=driver_id==user.id, back_populates="rides_as_driver")
rider = db.Relationship('User', primaryjoin=rider_id==user.id, back_populates="rides_as_rider")
class User:
rides_as_rider = db.Relationship('Ride', primaryjoin=id==ride.rider_id, back_populates="rider")
rides_as_driver = db.Relationship('Ride', primaryjoin=id==ride.driver_id, back_populates="driver")