问题
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?
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/27566614/django-cascade-delete-and-post-delete-signal