Opened 7 years ago
Last modified 7 years ago
#29398 closed Cleanup/optimization
Cascade deletion doesn't invoke .delete() on the cascaded objects — at Version 2
| Reported by: | Daniel Quinn | Owned by: | nobody |
|---|---|---|---|
| Component: | Documentation | Version: | 1.11 |
| Severity: | Normal | Keywords: | delete cascade |
| Cc: | Triage Stage: | Accepted | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description (last modified by )
I understand that when using .delete() on a queryset, the object(s) in question won't have their .delete() method executed. However, if you're explicitly calling .delete() on an object, I would expect that this would in turn call .delete() on any cascaded objects as well, and this appears not to be the case. Some example code for illustration:
class User(models.Model):
name = models.CharField(max_length=16)
def delete(self, *args, **kwargs):
print("This is executed")
super().delete(*args, **kwargs)
class Business(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
def delete(self, *args, **kwargs):
print("This isn't executed :-(")
super().delete(*args, **kwargs)
# This will run User.delete() and delete the associated business, but *not* execute Business.delete()
User.objects.first().delete()
It's unclear whether this is a bug or intentional, but I didn't see anything about this in the documentation and it surprised me today, so I thought I would mention it. I generally don't like signals (too much magic) but is that the preferred method for handling deletion special cases?
Change History (2)
comment:1 by , 7 years ago
| Description: | modified (diff) |
|---|
comment:2 by , 7 years ago
| Description: | modified (diff) |
|---|