简体   繁体   English

SQLAlchemy 外键约束混淆

[英]SQLAlchemy Foreign key constraint confusion

I just want to delete a survey record in the Survey table, and the record in SurveyQuestions should be deleted too.我只想删除Survey表中的一个调查记录, SurveyQuestions的记录也应该删除。 I've tried cascade , passive_deletes , and ondelete .我尝试过cascadepassive_deletesondelete I keep getting the foreign key violation error no matter what I try from the documentation.无论我从文档中尝试什么,我都会不断收到外键违规错误。 Is it the way my tables are set up?这是我的桌子的设置方式吗?

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'))

Are there other models that use Survey as a foreign key?是否有其他模型使用Survey作为外键? Perhaps the foreign key violation happens because you didn't specify ondelete strategy in another model that points to Survey可能发生外键违规是因为您没有在指向Survey另一个模型中指定ondelete策略

So I had to drop all the tables using Base.metadata.drop_all(engine) before the foreign key relations would take effect.所以我必须在外键关系生效之前使用Base.metadata.drop_all(engine)删除所有表。 Since then we have adopted alembic to remedy this issue through the use of migrations.从那时起,我们采用alembic来通过使用迁移来解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM