简体   繁体   中英

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

Currently, I am using Django with a MySQL backend database.

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. 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 .

My question is, what will MySQL attempt to delete first should I delete Parent ? Will it delete Parent first then try to delete the Child rows, or the other way around?

What Django does when you delete an object -> It deletes all children first, and then deletes the object.

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 ?

You can't create a child without a parent , and you can't create a parent with a last_child .

So when you make your last_child null-able, on parent.delete you need to set last_child = null , and then call parent.delete() . And I guess you will be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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