Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask foreign_keys still shows AmbiguousForeignKeysError

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

like image 460
M Rijalul Kahfi Avatar asked Mar 14 '15 00:03

M Rijalul Kahfi


1 Answers

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.

like image 88
M Rijalul Kahfi Avatar answered Oct 14 '22 16:10

M Rijalul Kahfi