Search code examples
djangodjango-models

How to on_delete=models.CASCADE both ways on OneToOne model?


I have 2 models:

   class A(models.Model):
        name = models.CharField(max_length=50)


        def __str__(self):
            return "%s the place" % self.name

    class B(models.Model):
        a = models.OneToOneField(Place,on_delete=models.CASCADE)
        name = models.CharField(max_length=50)

I want:

  1. If A is deleted B will be deleted (works)
  2. If B is deleted also A is deleted

Solution

  • I think you can use two main options:

    1 - Create a signal post_delete on Model B, which will delete the record on Model A: https://docs.djangoproject.com/en/3.2/ref/signals/#django.db.models.signals.post_delete

    2 - Override the delete method on Model B: Override django's model delete method for bulk deletion

    As it was pointed by @iserranoe in the comments, solution 2 will not work properly when deleting multiple models. Because of that, and to avoid overriding Django default methods, I strongly suggest using post_delete signals