Django for many relationships on delete

I have the following models:

class Branch(models.Model):
    releases = models.ManyToManyField(Release)


class Release(models.Model):
    #fields

      

What is the default behavior of django when deleting a release object (in my case?) Will it delete all branch objects specific to that version or not? My guess is that if I don't have it set null = True, then if I try to uninstall all the issues, it will give me an IntegrityError correctly, because the issues will be empty. If I set it to null = True, then I am assuming that it will just leave the issues as an empty list if the associated object is deleted. Is it possible to delete all linked branches when deleting a release and the branch object has no linked object in releases?

eg

r1 = Release()
r1.save()
r2 = Release()
r2.save()
b1 = Branch()
b1.save()
b1.releases.add(r1)
b2 = Branch()
b2.save()
b2.releases.add(r2)
r1.delete() #this should delete b1 because releases is empty

      

Is this behavior possible?

+3


source to share


1 answer


null

does not affect the relationship ManyToMany

.

In Django, M2M relationships are represented through a staging table that is automatically generated. The addition null=True/False

does not affect how this staging table is created, and the parent always has no children.

blank is an option that affects the ability to create a parent with or without children, but this is not a database level constraint, it is just a code level check.



The way to implement cascading delete that you are looking for is using the post_delete signal . Something like:

from django.db.models.signals import post_delete
from django.dispatch import receiver

class Branch(models.Model):
    releases = models.ManyToManyField(Release)

class Release(models.Model):
    #fields

@receiver(post_delete, sender=Release)
def cascade_delete_branch(sender, instance, **kwargs):
   # code to handle Branch removal

      

+1


source







All Articles