使用关联模式在SQLAlchemy中定向多对多自引用ORM

时间:2017-09-11 19:57:07

标签: python orm sqlalchemy

我试着找了一段时间,并没有找到解决我特定问题的方法,所以我提前道歉。

假设我有以下模型,其中包含表Users and Follows:

     ________         src      ________ 
    |  User  |-1------------*-| Follow | 
    |--------|                |--------| 
    | id     |                | src_id |
    |        |                | dst_id |
    |        |                | string |
    |________|-1------------*-|________|
                      dst

请注意,根据外键,有不同的语义。

我试图通过"关联模式实现这一目标" (described here),但我可以让它发挥作用。它看起来像这样:

class Follow(Base):
    __tablename__ = 'follows'
    #
    src_id = Column(BigInteger, ForeignKey('users.id'), primary_key=True)
    dst_id = Column(BigInteger, ForeignKey('users.id'), primary_key=True)

    src = relationship("User", back_populates="followers", foreign_keys=[src_id])
    dst = relationship("User", back_populates="followees", foreign_keys=[dst_id])

    kind = Column(String(16))

class User(Base):
    __tablename__ = 'users'

    name = Column(String(20))

    followers = relationship("UUEdge", primaryjoin="User.id==UUEdge.dst_id")
    followees = relationship("UUEdge", primaryjoin="User.id==UUEdge.src_id")

这可能吗?我做错了吗?

干杯

P.S。

类似的问题,不回答我的:

How can I achieve a self-referencing many-to-many relationship on the SQLAlchemy ORM back referencing to the same attribute?

1 个答案:

答案 0 :(得分:0)

这就是我使用连接表在项目中实现关注者关系的方式。

followers = Table(
    'followers', metadata,
    Column('user_id', Integer,
        ForeignKey('users.user_id'), primary_key=True),
    Column('follower_id', Integer,
        ForeignKey('users.user_id'), primary_key=True),
)

class User(Base):

    __tablename__ = 'users'

    user_id = Column(Integer, primary_key=True)

    followers = relationship(
        'User', secondary=followers, cascade='all', lazy='dynamic',
        primaryjoin=followers.c.user_id == user_id,
        secondaryjoin=followers.c.follower_id == user_id)


# do some following!
user = session.query(User).get(..)
follower = User()
user.followers.append(follower)