如何在 MySQL 中临时禁用外键约束?

2021-11-20 00:00:00 django django-models sql mysql

是否可以暂时禁用 MySQL 中的约束?

Is it possible to temporarily disable constraints in MySQL?

我有两个 Django 模型,每个模型都有一个指向另一个模型的外键.由于外键约束,删除模型的实例会返回错误:

I have two Django models, each with a foreign key to the other one. Deleting instances of a model returns an error because of the foreign key constraint:

cursor.execute("DELETE FROM myapp_item WHERE n = %s", n)
transaction.commit_unless_managed()  #a foreign key constraint fails here

cursor.execute("DELETE FROM myapp_style WHERE n = %s", n)
transaction.commit_unless_managed()

是否可以暂时禁用约束并删除?

Is it possible to temporarily disable constraints and delete anyway?

推荐答案

Try DISABLE KEYS

SET FOREIGN_KEY_CHECKS=0;

确保

SET FOREIGN_KEY_CHECKS=1;

之后.

相关文章