使用 SQLAlchemy 为 FastAPI 设置外键
Setting Foreign Keys with SQLAlchemy for FastAPI
我的模型模块中有以下表格,我必须在它们的某些属性之间设置外键关系。但是,我失败了。
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")
我正在尝试在 Exercise.animation_id 和 Animation.id 之间建立关系。
我尝试在代码中添加 ForeignKey('Animation.id')) 但它不起作用。
我想不出别的了。
提前致谢。
通过从 MyISAM 切换到 InnoDB 解决了这个问题。事实证明 MyISAM 不支持外键。
class Exercise(Base):
__tablename__= "Exercise"
__table_args__= {
'mysql_engine':'InnoDB'
}
我的模型模块中有以下表格,我必须在它们的某些属性之间设置外键关系。但是,我失败了。
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")
我正在尝试在 Exercise.animation_id 和 Animation.id 之间建立关系。 我尝试在代码中添加 ForeignKey('Animation.id')) 但它不起作用。
我想不出别的了。 提前致谢。
通过从 MyISAM 切换到 InnoDB 解决了这个问题。事实证明 MyISAM 不支持外键。
class Exercise(Base):
__tablename__= "Exercise"
__table_args__= {
'mysql_engine':'InnoDB'
}