我使用SQLAlchemy的遷移跟蹤數據庫的變化和我遇到的問題與刪除的外鍵。我有兩個表,t_new是一個新表,而t_exists是一個現有的表。我需要添加t_new,然後向t_exists添加一個外鍵。然後我需要能夠扭轉操作(這是我遇到麻煩的地方)。如何在SQLAlchemy中刪除外鍵約束?
t_new = sa.Table("new", meta.metadata,
sa.Column("new_id", sa.types.Integer, primary_key=True)
)
t_exists = sa.Table("exists", meta.metadata,
sa.Column("exists_id", sa.types.Integer, primary_key=True),
sa.Column(
"new_id",
sa.types.Integer,
sa.ForeignKey("new.new_id", onupdate="CASCADE", ondelete="CASCADE"),
nullable=False
)
)
這工作得很好:
t_new.create()
t_exists.c.new_id.create()
但這並不:
t_exists.c.new_id.drop()
t_new.drop()
試圖刪除外鍵列給出了一個錯誤:1025,上重命名「錯誤」。 \ my_db_name \#sql-1b0_2e6'改爲'。\ my_db_name \ exists'(errno:150)「
如果我用原始SQL執行此操作,我可以刪除f手動鍵入關鍵字然後刪除列,但我一直無法弄清楚如何使用SQLAlchemy刪除外鍵?我如何刪除外鍵,然後刪除列?
對於任何可能遇到此問題的人 - ForeignKeyConstraint需要從'migrate'中導入,而不是從'sqlalchemy'中導入。 – mjallday