SQLAlchemy关系加入多个外键

时间:2015-06-19 14:37:26

标签: python sqlalchemy

使用SQLAlchemy,我无法确定如何映射以下关系:用户可以跟随'由其他用户,从而成为一个领导者'与'粉丝'。

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

从文档中,我认为这样的声明会有

some_user.followers

执行'用户'和' users_followers'表格' users.id = users_followers.leader_id'其中' user.id = some_user.id'。

然而,这会产生错误(类似于How to specify table relationships in SQLAlchemy with multi-level/multiple joins?)。虽然建议的解决方案允许我解决这个问题,但它阻止了使用级联' SQLAlchemy关系的属性,这样当删除用户时,相应的UserFollower对象也会被删除。

总结:如何将关系连接到具有多个外键的表引用相同的键并仍然保留级联(删除)?

1 个答案:

答案 0 :(得分:3)

如果您阅读SQLAlchemy文档的Self-Referential Many-to-Many Relationship部分,您将意识到您拥有经典的多对多关系。如果您根据文档定义此关系,级联将正常工作:

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',
    )