各ユーザーは多くの友達を持つことができるので、ユーザーを他のユーザーにマップするテーブルUsersとテーブルFriendsがあります。この関係は明らかに対称的です。ユーザーAがユーザーBの友達である場合、ユーザーBもユーザーAの友達である場合、この関係を1回だけ保存します。Friendsテーブルには、2つのユーザーIDの他に追加のフィールドがあるため、関連付けオブジェクトを使用する必要があります。
この関係をUsersクラス(宣言ベースを拡張する)で宣言スタイルで定義しようとしていますが、これを行う方法がわからないようです。プロパティfriendsを介して特定のユーザーのすべての友達にアクセスできるようにしたいので、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.
私はこの時点で、多くの失敗した試みのために完全に混乱しており、上記で複数の愚かな間違いを犯した可能性があることを認めなければなりません。