Flask migrate error – foreign key associated with column could not find table with which to generate a foreign key to target column

Question:

I have two models as following in different files. When I run flask db migrate I get this error.

raise exc.NoReferencedTableError(
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'datasets.user_id' could not find table 'user' with which to generate a foreign key to target column 'id'

What am i doing wrong? Please help me out, thanks.

class User(Model):
    __tablename__ = "users"
    id = Column(db.Integer, primary_key=True)
    email = Column(db.String(64), unique=True, index=True)
    username = Column(db.String(15), unique=True, index=True)
    role_id = Column(db.Integer, db.ForeignKey("roles.id"))
    userdataset = db.relationship("Dataset", backref="user")

class Dataset(db.Model):
    __tablename__ = 'datasets'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True, unique=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
Asked By: aysberna

||

Answers:

If you set the value of the foreign key in the dataset table to users.id, it will work.

Answered By: iremdoganci

As your table name is users you need to set foreign key using users.id

Answered By: Premal Parekh
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.