模型定义:
class Follow(db.Model): __tablename__ = 'tb_follow' id = db.Column(db.Integer, primary_key=True) userid = db.Column(db.Integer, db.ForeignKey('tb_user.id'), nullable=False) followid = db.Column(db.Integer, db.ForeignKey('tb_user.id'), nullable=False) createTime = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now) user = db.relationship('User') follower = db.relationship('User') def __init__(self, userid, followid): self.userid = userid self.followid = followid def __repr__(self): return '' % (self.user, self.follower, self.createTime)
报错:sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship
model中有两个外键引用同一个user表,在db.relationship()时无法确定如何对应。所以,需要借助relationship函数其它参数。如foreign_keys=[xxx]
故模型改为:
class Follow(db.Model): __tablename__ = 'tb_follow' id = db.Column(db.Integer, primary_key=True) userid = db.Column(db.Integer, db.ForeignKey('tb_user.id'), nullable=False) followid = db.Column(db.Integer, db.ForeignKey('tb_user.id'), nullable=False) createTime = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now) user = db.relationship('User', foreign_keys=userid) follower = db.relationship('User', foreign_keys=followid) def __init__(self, userid, followid): self.userid = userid self.followid = followid def __repr__(self): return '' % (self.user, self.follower, self.createTime)
关键:
user = db.relationship('User', foreign_keys=userid)follower = db.relationship('User', foreign_keys=followid)