[英]SQLAlchemy Foreign key constraint confusion
我只想删除Survey
表中的一个调查记录, SurveyQuestions
的记录也应该删除。 我尝试过cascade
、 passive_deletes
和ondelete
。 无论我从文档中尝试什么,我都会不断收到外键违规错误。 这是我的桌子的设置方式吗?
class Survey(Base):
__tablename__ = 'survey'
id = Column(Integer, primary_key=True, autoincrement=True)
survey_description = Column(String(100))
survey_start_date = Column(Date)
survey_end_date = Column(Date)
survey_is_active = Column(Boolean)
survey_questions = relationship(Question, secondary='survey_questions',cascade="all, delete",passive_deletes=True)
class SurveyQuestions(Base):
__tablename__ = 'survey_questions'
id = Column(Integer, primary_key=True, autoincrement=True)
survey_id = Column(Integer, ForeignKey('survey.id', ondelete='CASCADE'))
question_id = Column(Integer, ForeignKey('question.id', ondelete='CASCADE'))
是否有其他模型使用Survey
作为外键? 可能发生外键违规是因为您没有在指向Survey
另一个模型中指定ondelete
策略
所以我必须在外键关系生效之前使用Base.metadata.drop_all(engine)
删除所有表。 从那时起,我们采用alembic来通过使用迁移来解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.