Flask foreign_keys still shows AmbiguousForeignKey

2020-07-11 07:25发布

问题:

I have two foreign keys in an entity refering to another entity. Here is how it looks

    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])

and

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

However, it still shows me an error saying

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

The above workaround is what I get from some other posts. I have checked and changed many times, and still no luck. I wonder if it's already correct or there is something I miss. Need help

回答1:

Finally, I got the workaround after trying to figure out. In my case, I don't have to put backref in Review class. Instead, I should put the User backref in User class itself. So, it should look like below

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)

Here, both types of User have many Reviews. Then, when I need to get the list of reviews of both User, what I can do is

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

And I am no longer running across this error.