I have models like this:
class Parent(models.Model):
pass
class Child(models.Model):
parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
class Log(models.Model):
parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
detail = models.TextField()
I also have a signal like this:
@receiver(post_delete, sender=Child)
def handle_delete_child(sender, instance, **kwargs):
log = Log(parent = instance.parent, detail="child deleted")
log.save()
Now, if I try to delete the parent, I can see with debug on that the steps are going like this:
- Delete parent's logs.
- Delete parent's children (causing new log to be written as per the signal).
- Try to delete parent, but fails with "Cannot delete or update a parent row: a foreign key constraint fails", I think on the log created in step 2.
If I was able to specify that #2 should happen before #1, I think that would solve the problem, but I cannot find any reference to such things in the docs. Even a creative solution like a new signal or a model method override would be welcome.