Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I Use flask-SQLAlchemy to create databases, but I get this error:

"sqlalchemy.exc.NoForeignKeysError sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship User.refund - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression."

I have a User model schema defined as:

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True)
    username = db.Column(db.String(64), unique=True, index=True)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    password_hash = db.Column(db.String(128))
    confirmed = db.Column(db.Boolean, default=False)
    name = db.Column(db.String(64))
    location = db.Column(db.String(64))
    about_me = db.Column(db.Text())
    member_since = db.Column(db.DateTime(), default=datetime.utcnow)
    last_seen = db.Column(db.DateTime(), default=datetime.utcnow)
    avatar_hash = db.Column(db.String(32))
    posts = db.relationship('Post', backref='author', lazy='dynamic')
    comments = db.relationship('Comment', backref='author', lazy='dynamic')
    purchases = db.relationship("Purchase", backref='author', lazy='dynamic')
    refund = db.relationship("Refund", backref='author', lazy='dynamic')
class Refund(db.Model):
    __tablename__ = "Refund"
    id = db.Column(db.Integer, primary_key=True)
    purchase_id = db.Column(db.Integer, db.ForeignKey("Purchase.id"))
    medicine_id = db.Column(db.Integer, db.ForeignKey("inventory.medicine_id"))
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)

Why do I get this error?

You have other tables as seen in your db.relationship() calls. The Refund model is correctly associated with the User table. So, there is a likelihood that the error you are getting stems from how you are creating the relationship with/between other models. – Gitau Harrison Apr 25, 2021 at 6:25

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.