我正在使用 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,“将 '.\my_db_name\#sql-1b0_2e6' 重命名为 '.\my_db_name\exists' 时出错(错误号:150)”
如果我使用原始 SQL 执行此操作,我可以手动删除外键然后删除列,但我无法弄清楚如何使用 SQLAlchemy 删除外键?如何删除外键,然后删除列?