首页 > 解决方案 > Setting Foreign Keys with SQLAlchemy for FastAPI

问题描述

I have the following tables in my models module and I have to set Foreign Key relations between some of their attributes. However, I am failing.

class Exercise(Base):
   __tablename__= "Exercise"
   id=Column(Integer, primary_key= True) 
   name=Column(VARCHAR(250))
   animation_id=Column(Integer, ForeignKey('Animation.id')) #foreign key -> animation.id
   animation=relationship("Animation", back_populates="exercise")
   

class Animation(Base):
   __tablename__="Animation"
   id=Column(Integer,primary_key=True,index=True,autoincrement=True)
   name=Column(VARCHAR(250))
   description=Column(VARCHAR(250))
   exercise=relationship("Exercise", back_populates="animation")

Im trying to create a relationship between Exercise.animation_id and Animation.id. I tried adding ForeignKey('Animation.id')) as in the code but it did not work.

I can't think of anything else. Thanks in advance.

标签: pythonpython-3.xsqlalchemyfastapi

解决方案


Fixed the issue by switching to InnoDB from MyISAM. Turns out MyISAM does NOT support foreign keys.

class Exercise(Base):
    __tablename__= "Exercise"
    __table_args__= {
        'mysql_engine':'InnoDB'
    }

推荐阅读