5

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
  • Did you ever find the solution to this? I spent some time trying to find an answer but was unable to get it to work. Commented Mar 19, 2015 at 4:01

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.