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

2024-10-06 12:38:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着找了很长时间,没有找到解决我具体问题的办法,所以我提前道歉。你知道吗

假设我有以下带有表Users的模型,如下所示:

     ________         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")

这可能吗?我做错什么了吗?你知道吗

干杯

附言

类似的问题没有回答我的问题:

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


Tags: srcidbasebackcolumnusersclassdst
1条回答
网友
1楼 · 发布于 2024-10-06 12:38:05

这就是我在项目中使用联接表实现跟随者关系的方式。你知道吗

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)

相关问题 更多 >