我正在使用SQLAlchemy Migrate来跟踪数据库更改,但在删除外键时遇到了问题。我有两个表,t_new是新表,t_exists是现有表。我需要添加t_new,然后添加一个外键到t_exists。然后我需要能够撤消该操作(这就是我遇到问题的地方)。
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,“Error on rename of '.\my_db_name\#sql-1b0_2e6' to '.\my_db_name\exists' (errno: 150)”
如果我使用原始SQL执行此操作,则可以手动删除外键,然后删除该列,但我无法找出如何使用SQLAlchemy删除外键? 如何删除外键,然后再删除该列呢?
migrate
而不是sqlalchemy
中导入。 - mjalldaydrop
方法,但是我成功地使用op.drop_constraint(_FK_NAME, _TABLE_NAME, type_="foreignkey")
实现了相同的效果,并通过以下方式创建:op.create_foreign_key(_FK_NAME, _TABLE_NAME, "dest_table", ["src_column"], ["dest_column"])
。 - giuliano-oliveira