gpt4 book ai didi

python - Flask foreign_keys 仍然显示 AmbiguousForeignKeysError

转载 作者:可可西里 更新时间:2023-11-01 06:45:46 27 4
gpt4 key购买 nike

我在一个实体中有两个外键引用另一个实体。这是它的样子

    class Review(db.Model):
__tablename__ = 'Review'
id = db.Column(db.Integer, primary_key = True)
user_id = db.Column(db.Integer, db.ForeignKey('User.id'), nullable=False)
business_user_id = db.Column(db.Integer, db.ForeignKey('User.id'), nullable=False)
user = db.relationship('User', foreign_keys=[user_id])
business_user = db.relationship('User', foreign_keys=[business_user_id])

class User(db.Model):
__tablename__ = 'User'
id = db.Column(db.Integer, primary_key = True)
reviews = db.relationship('Review', backref='user',
lazy='dynamic')

但是,它仍然向我显示错误信息

there are multiple foreign key paths linking the tables. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table

上述解决方法是我从其他一些帖子中得到的。我已经检查并更改了很多次,但仍然没有运气。我想知道它是否已经正确或者我想念什么。需要帮助

最佳答案

经过一番摸索,终于找到了解决办法。就我而言,我不必将 backref 放在 Review 类中。相反,我应该将 User backref 放在 User 类本身中。所以,它应该如下所示

class Review(db.Model):
__tablename__ = 'Review'
id = db.Column(db.Integer, primary_key = True)
user_id = db.Column(db.Integer, db.ForeignKey('User.id'), nullable=False)
business_user_id = db.Column(db.Integer, db.ForeignKey('User.id'), nullable=False)
user = relationship('User', backref='user_reviews', foreign_keys=user_id)
business_user = relationship("User", backref='business_user_reviews', foreign_keys=[business_user_id])

class User(db.Model):
__tablename__ = 'User'
id = db.Column(db.Integer, primary_key = True)

在这里,两种类型的用户都有很多评论。然后,当我需要获取两个 User 的评论列表时,我可以做的是

user = User.query.get(id)
user_reviews = User.user_reviews
business_user_reviews = user.business_user_reviews

而且我不再遇到此错误。

关于python - Flask foreign_keys 仍然显示 AmbiguousForeignKeysError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29044173/

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