Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django cascade delete and post_delete signal

In my application post_delete signals being recorded in a specific model and when it was removed.

class A(models.Model):
    ...

class B(models.Model):
    a = models.ForeignKey('A')

class C(models.Model):
    b = models.ForeignKey('B')

def log_delete(sender, instance, **kwargs):
    logging

post_delete.connect(log_delete, sender = A)
post_delete.connect(log_delete, sender = C)

When you delete an instance of A cascade delete occurs removing B and C instances. How can I disable signal for child instances on cascade delete by django?

like image 771
Andrey Fedosenko Avatar asked Dec 19 '14 12:12

Andrey Fedosenko


2 Answers

Not an elegant solution as what user2059857 suggested, but a LOT simpler to implement:

Add a field to model A:

being_deleted = models.BooleanField(default=False)`

Set this to True when A model pre_delete signal is fired:

@receiver(models.signals.pre_delete, sender=A)
def a_pre_delete(sender, instance, **kwargs):
    instance.being_deleted = True
    instance.save()

Check if being_deleted of your A instance is True in every pre_delete of child models and act accordingly.

like image 70
Augusto Destrero Avatar answered Sep 22 '22 12:09

Augusto Destrero


Short answer:

You can't.

Long answer:

You need to override your .delete methods of your Model and your model manager QuerySet

I have accomplished some similar task by having the instance which the delete was called on passed along by the pre/post delete signals.

Here is the code https://gist.github.com/ar45/9c1448a91bcc94997ff0

like image 30
user2059857 Avatar answered Sep 23 '22 12:09

user2059857