3

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
user3541631
  • 3,686
  • 8
  • 48
  • 115

1 Answers1

4

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

Tiago Gomes
  • 357
  • 4
  • 12
  • Which one is better? – chococroqueta Jan 12 '22 at 10:21
  • So, overriding the delete method is not working when deleting multiple models at the same time at the admin site. You have to override other methods, so I guess adding signals would be better. Anyway, it is dicussed in the second link. – chococroqueta Jan 12 '22 at 11:08
  • Sorry, @iserranoe, this answer is really old. Nowadays, I think the best solution is to use Django signals, or solution 1. In fact, nowadays I try not to override Django methods. I will update the link to use the latest version of docs and put your comment on solution 2. – Tiago Gomes Jan 13 '22 at 11:43
  • Thank you Tiago! Perfect, then I'm more confident about using signals, which is the option I'm finally using. – chococroqueta Jan 13 '22 at 12:43