Flask foreign_keys still showing AmbiguousForeignKeysError

I have two foreign keys in an object referencing another object. Here is what it looks like

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, this still shows me an error saying

There are several foreign key paths connecting tables. Specify 'foreign_keys' containing a list of those columns that should be considered as containing a foreign key reference for the parent Table

The above workaround is what I get from some other messages. I checked and changed many times, and I still had no luck. I wonder if this is right or something I am missing. Need help

+6
source share
1 answer

Finally, I got a workaround trying to figure it out. In my case, I do not need to put backref in the Review class. Instead, I have to put the backref user in the User class. So it should look 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 users have many reviews. Then, when I need to get a list of reviews about all User , I can do this

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

And I no longer encounter this error.

+6
source

Source: https://habr.com/ru/post/983776/


All Articles