Sqlalchemy Relationship Raise Argument Error When Creating Backref
I am trying to build a one to many relationship so that each cafe can have many reviews. However, SQLAlchemy raises an ArgumentError when defining the relationship. How do I fix th
Solution 1:
When SQLAlchemy tries to create the backref for the Cafe.cafes
relationship called cafe
on Review
, it finds the column you named cafe
and raises an error that it can't use the same name.
Give your foreign keys different names than your relationships/backrefs.
cafe_name = db.Column(db.ForeignKey(Cafe.name))
Alternatively, it can be easier to keep track of names when the foreign key and relationship are defined in the same model.
class Cafe(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
class Review(db.Model):
id = db.Column(db.Integer, primary_key=True)
cafe_id = db.Column(db.ForeignKey(Cafe.id))
cafe = db.relationship(Cafe, backref='reviews')
Post a Comment for "Sqlalchemy Relationship Raise Argument Error When Creating Backref"