SQLAlchemy同一个表的多个外键:InvalidRequestError

时间:2015-08-19 18:46:30

标签: python flask sqlalchemy flask-sqlalchemy

我有两个表User表和Follow表。 User表格有idFollow表格有两列FollowerFollowing,它们是外键,与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.

问题是什么,我该如何解决?感谢。

0 个答案:

没有答案