python - SQLAlchemy Relationship Join with Multiple Foreign Keys -


using sqlalchemy, i'm having trouble figuring out how map following relation: user can 'followed' other users, becoming 'leader' 'followers'.

class user( base ):     __tablename__ = 'users'     id = column( integer, primary_key = true )     followers = relationship( 'user', primaryjoin = 'and_( user.id == userfollower.leader_id )', cascade = 'all' )     leaders = relationship( 'user', primaryjoin = 'and_( user.id == userfollower.follower_id )', cascade = 'all' )  class userfollower( base ):     __tablename__ = 'users_followers'     leader_id = column( integer, foreignkey( 'users.id' ), primary_key = true )     follower_id = column( integer, foreignkey( 'users.id' ), primary_key = true )     follower = relationship( 'user', uselist = false, foreign_keys = [ follower_id ] )     leader = relationship( 'user', uselist = false, foreign_keys = [ leader_id ] ) 

from documentation under impression such declaration have

some_user.followers 

perform join of 'users' , 'users_followers' tables on 'users.id = users_followers.leader_id' 'user.id = some_user.id'.

however, yields error (similar how specify table relationships in sqlalchemy multi-level/multiple joins?). although proposed solution allows me work around issue, prevents use of 'cascading' property of sqlalchemy's relationships when deleting user, corresponding userfollower objects deleted.

in summary: how can have relationships joined table multiple foreign keys referring same key , still preserve cascading (deletion)?

if read self-referential many-to-many relationship section of sqlalchemy documentation, realise have classical many-to-many relationship. if define relation according documentation, cascades work fine:

users_followers = table(     'users_followers', base.metadata,     column('leader_id', foreignkey('users.id'), primary_key=true),     column('follower_id', foreignkey('users.id'), primary_key=true), )   class user(base):     __tablename__ = 'users'     id = column(integer, primary_key=true)     name = column(string)      followers = relationship(         'user',         secondary=users_followers,         primaryjoin=id == users_followers.c.leader_id,         secondaryjoin=id == users_followers.c.follower_id,         backref="leaders",         cascade='all',     ) 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -