Django reverse (on_delete) protection on a model instance

234 Views Asked by At

Is is possible to protect a model in a reverse relationship. For instance in the models below:-

class Foo(models.Model):
    foo_field1 = models.CharField(max_length=56, unique=True)

class Bar(models.Model):
    bar_field1 = models.ForeignKey(Foo, on_delete=models.PROTECT, blank=True)
    bar_field2 = models.CharField(max_length=56, unique=True)

If an attempt is made to delete an instance of Foo, it wont be deleted as the on_delete attribute on Bar is set to models.PROTECT. So, is it possible to extend that protection both ways? That is, if an attempt is made to delete an instance of Bar, so can it be protected just like Foo, can someone suggest a solution?.

1

There are 1 best solutions below

1
On

I don't have a full solution for you, but I would suggest looking into using a Django Signal, specifilly pre-delete. You would in that signal check if bar_field_1 in instance of Bar is null and abort the deletion if it is not null.