简体   繁体   English

(Django)MySQL外键级联是否首先删除父级或子级

[英](Django) Does MySQL foreign key cascade delete parent or children first

Currently, I am using Django with a MySQL backend database. 当前,我将Django与MySQL后端数据库一起使用。

Let us having the following database schema 让我们拥有以下数据库架构

class Parent(models.Model):
     parent_id  = models.BigAutoField(primary_key=True)
     last_child = models.ForeignKey('Child', on_delete=models.PROTECT)

class Child(models.Model):
     child_id = models.BigAutoField(primary_key=True)
     parent   = models.ForeignKey('Parent', on_delete=models.CASCADE)

Each parent can have multiple children, but each child can only have one parent. 每个父母可以有多个孩子,但每个孩子只能有一个父母。 The field last_child points to the last child birthed by the parent. 字段last_child指向父母last_child的最后一个孩子。 What I am trying to express via this schema is 我想通过这种模式表达的是

  • The last child cannot die (be deleted) as long as its parent is still alive 只要最后一个孩子还活着,他就不会死亡(被删除)

  • All children die when the parent dies 父母去世时所有子女都去世

However I have some concerns regarding database integrity, because of the conflicting PROTECT vs CASCADE . 但是,由于PROTECTCASCADE的冲突,我对数据库的完整性有些担忧。

My question is, what will MySQL attempt to delete first should I delete Parent ? 我的问题是,MySQL应该先尝试删除哪些内容,然后再删除Parent Will it delete Parent first then try to delete the Child rows, or the other way around? 它会先删除Parent然后尝试删除Child行,还是相反?

What Django does when you delete an object -> It deletes all children first, and then deletes the object. Django在删除对象时的作用->首先删除所有子对象,然后再删除对象。

Your schema is a little bit strange, you need to make your last_child object null-able , because how are you gonna create a parent without children ? 您的架构有点奇怪,您需要使last_child对象为可null-able ,因为您将如何创建没有childrenparent

You can't create a child without a parent , and you can't create a parent with a last_child . 您不能创建没有parentchild ,也不能创建带有last_childparent

So when you make your last_child null-able, on parent.delete you need to set last_child = null , and then call parent.delete() . 因此,当您使last_child null时,需要在parent.delete上设置last_child = null ,然后调用parent.delete() And I guess you will be fine. 我想你会没事的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM