Home > database >  Flask Rest API SQLAlchemy foreign key error
Flask Rest API SQLAlchemy foreign key error

Time:02-11

I got SQLALchemy error, when I tried "flask db migrate"

NoReferencedTableError: Foreign key associated with column 'user.menu_id' could not find table 'menu' with which to generate a foreign key to target column 'id

Menu table

class Menu(db.Model):
   __tablename__ = 'menus'
   id = db.Column(db.Integer(), primary_key=True)
   name = db.Column(db.String(64), index=True, unique=True)
   price = db.Column(db.String(64), index=True, unique=True)
   description = db.Column(db.String(64), index=True, unique=True)
   picture = db.Column(db.String(64), index=True, unique=True)
   create_date = db.Column(db.DateTime, default=datetime.utcnow)
   users = db.relationship('User', backref="menu", lazy=True)

User table

class User(Model):
""" User model for storing user related data """

   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)
   name = Column(db.String(64))
   password_hash = Column(db.String(128))
   admin = Column(db.Boolean, default=False)

   joined_date = Column(db.DateTime, default=datetime.utcnow)    
   userdataset = db.relationship("Dataset", backref="user", lazy="dynamic")
   menu_id = Column(db.Integer(), db.ForeignKey('menu.id'), nullable=False)
   def __init__(self, **kwargs):
      super(User, self).__init__(**kwargs)

How can ı solve this problem? Where am i doing wrong?

CodePudding user response:

You have renamed your 'Menu' table to 'menus' with this __tablename__ property in your 'Menu' model:

__tablename__ = 'menus'

You then try to reference to the 'Menu' table, when in fact, its name has been changed to 'menus'. The simplest way to solve this would be to change your User.menu_id column to this:

menu_id = Column(db.Integer(), db.ForeignKey('menus.id'), nullable=False)

Another way of fixing this issue would be modifying the __tablename__ property to 'menu'. (You could also just delete it.)

  • Related