【发布时间】:2016-08-26 07:31:34
【问题描述】:
我正在尝试使用 SQLAlchemy 上的声明性来实现自引用多对多关系。
关系代表两个用户之间的友谊。在线我发现(在文档和谷歌中)如何建立一个自我参照的 m2m 关系,以某种方式区分角色。这意味着在这种 m2m 关系中,用户 A 是,例如,用户 B 的老板,所以他将他列为“下属”属性或你有什么。以同样的方式,UserB 将 UserA 列在“上级”下。
这没有问题,因为我们可以这样声明同一张表的反向引用:
subordinates = relationship('User', backref='superiors')
当然,“superiors”属性在类中并不显式。
无论如何,这是我的问题:如果我想反向引用到我调用反向引用的同一属性怎么办?像这样:
friends = relationship('User',
secondary=friendship, #this is the table that breaks the m2m
primaryjoin=id==friendship.c.friend_a_id,
secondaryjoin=id==friendship.c.friend_b_id
backref=??????
)
这是有道理的,因为如果 A 与 B 成为朋友,则关系角色是相同的,如果我调用 B 的朋友,我应该得到一个包含 A 的列表。这是完整的有问题的代码:
friendship = Table(
'friendships', Base.metadata,
Column('friend_a_id', Integer, ForeignKey('users.id'), primary_key=True),
Column('friend_b_id', Integer, ForeignKey('users.id'), primary_key=True)
)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
friends = relationship('User',
secondary=friendship,
primaryjoin=id==friendship.c.friend_a_id,
secondaryjoin=id==friendship.c.friend_b_id,
#HELP NEEDED HERE
)
抱歉,如果文字过多,我只想尽可能明确地说明这一点。我似乎无法在网上找到任何参考资料。
【问题讨论】:
标签: python many-to-many sqlalchemy self-reference