我正在尝试使用SQLAlchemy的声明式语法实现自引用的多对多关系。
这个关系表示两个用户之间的友谊。在网上我发现了(无论是在文档还是Google中)如何建立一个自引用的m2m关系,其中一些角色有所区别。这意味着在这个m2m关系中,例如UserA是UserB的老板,因此他在“下属”属性或其他属性下列出他。同样,UserB在“上司”属性下列出UserA。
这并不成问题,因为我们可以以以下方式在同一张表中声明backref:
subordinates = relationship('User', backref='superiors')
当然,在这个类中,'superiors'属性是没有显式声明的。
无论如何,这是我的问题:如果我想要在反向引用(backref)时引用正在调用backref的同一属性,该怎么办?就像这样:
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
)
如果这段文字太长的话,抱歉了。我只是想尽可能明确地描述问题。我在网上找不到任何参考资料。
all_friends
,而且你不会得到任何警告。有什么建议吗? - Vladimir Keleshev1,2
和2,1
)。您可以设置一个约束条件,即一个ID必须大于另一个ID,但是这样您需要跟踪哪些用户可以附加到哪些用户的“朋友”属性。 - Vladimir Keleshev