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?
The documentation for
on_delete
CASCADE says, "Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey." I guess that would be the documentation to clarify.