我有两个表User
表和Follow
表。 User
表格有id
。 Follow
表格有两列Follower
和Following
,它们是外键,与User
表的id
相关。
我希望能够轻松地将用户的关注者引用给用户所关注的人,因此我在SQLAlchemy中建立了一个关系,如下所示:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
...
Followers = db.relationship('Follow')
Following = db.relationship('Follow')
class Follow(db.Model):
id = db.Column(db.Integer, primary_key=True)
follower = db.Column(db.Integer, db.ForeignKey('accounts.id', onupdate='CASCADE', ondelete='CASCADE'))
following = db.Column(db.Integer, db.ForeignKey('accounts.id', onupdate='CASCADE', ondelete='CASCADE'))
我收到了AmbiguousForeignKeysError
,说明我应该添加foreign_keys
属性,所以我在看到this这样的问题之后就这样做了:
class User(db.Model):
...
Followers = db.relationship('Follow', foreign_keys='follower')
Following = db.relationship('Follow', foreign_keys='following')
但现在我收到此错误:
InvalidRequestError: When initializing mapper Mapper|User|accounts, expression 'follower' failed to locate a name ("name 'follower' is not defined"). If this is a class name, consider adding this relationship() to the <class 'myapp.views.models.User'> class after both dependent classes have been defined.
问题是什么,我该如何解决?感谢。