如何临时禁用MySQL中的外键约束? [英] How to temporarily disable a foreign key constraint in MySQL?

查看:285
本文介绍了如何临时禁用MySQL中的外键约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to temporarily disable constraints in MySQL?

我有两个Django模型,每个都有一个ForeignKey到另一个。由于ForeignKey约束,删除模型的实例会返回一个错误:

I have two Django models, each with a ForeignKey to the other one. Deleting instances of a model returns an error because of the ForeignKey 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?

推荐答案

尝试 DISABLE KEYS

SET FOREIGN_KEY_CHECKS=0;

确保

SET FOREIGN_KEY_CHECKS=1;

after。

这篇关于如何临时禁用MySQL中的外键约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆