gpt4 book ai didi

python - SQLAlchemy 通过关联对象声明多对多自连接

转载 作者:太空狗 更新时间:2023-10-29 18:18:17 26 4
gpt4 key购买 nike

我有一个用户表和一个将用户映射到其他用户的表 friend ,因为每个用户可以有很多 friend 。这种关系显然是对称的:如果用户 A 是用户 B 的 friend ,那么用户 B 也是用户 A 的 friend ,我只存储一次这种关系。 Friends 表除了两个用户 ID 之外还有其他字段,因此我必须使用关联对象。

我试图在 Users 类(它扩展了声明性基础)中以声明式的方式定义这种关系,但我似乎无法弄清楚如何做到这一点。我希望能够通过属性 friends 访问给定用户的所有 friend ,比如 friends = bob.friends。

解决这个问题的最佳方法是什么?我尝试了许多不同的设置来张贴在这里,但由于各种原因,它们都没有奏效。

编辑:我最近的尝试是这样的:

class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)

# Relationships
friends1 = relationship('Friends', primaryjoin=lambda: id==Friends.friend1ID)
friends2 = relationship('Friends', primaryjoin=lambda: id==Friends.friend2ID)


class Friends(Base):
__tablename__ = 'friends'
id = Column(Integer, primary_key=True)
friend1ID = Column(Integer, ForeignKey('users.id') )
friend2ID = Column(Integer, ForeignKey('users.id') )
status = Column(Integer)

# Relationships
vriend1 = relationship('Student', primaryjoin=student2ID==Student.id)
vriend2 = relationship('Student', primaryjoin=student1ID==Student.id)

然而,这会导致以下错误:

InvalidRequestError: Table 'users' is already defined for this MetaData instance.  Specify 'extend_existing=True' to redefine options and columns on an existing Table object.

我必须承认,在这一点上,由于多次失败的尝试,我感到非常困惑,并且可能在上面犯了不止一个愚蠢的错误。

最佳答案

这个特殊的异常是由多次描述表引起的,或者通过重复定义类映射(比如,在交互式解释器中,或者在可以多次调用的函数中),或者通过混合声明式类与表反射的映射。对于前一种情况,消除重复调用;如果您以交互方式进行,则启动一个新的解释器,或者消除额外的函数调用(对于单例/borg 对象来说可能是一个很好的用途)。

在后一种情况下,只需按照异常说明进行操作,将 __table_args__ = {'extend_existing': True} 添加为类定义中的额外类变量。仅当您确实确定表被正确描述了两次时才这样做,就像表反射一样。

关于python - SQLAlchemy 通过关联对象声明多对多自连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7309607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com