Opened 6 years ago

Closed 6 years ago

Last modified 6 years ago

#29398 closed Cleanup/optimization (fixed)

Clarify that cascade deletion doesn't invoke .delete() on the cascaded objects

Reported by: Daniel Quinn Owned by: Jacob Tomlinson
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 Daniel Quinn)

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 (6)

comment:1 by Daniel Quinn, 6 years ago

Description: modified (diff)

comment:2 by Daniel Quinn, 6 years ago

Description: modified (diff)

comment:3 by Tim Graham, 6 years ago

Component: UncategorizedDocumentation
Summary: Cascade deletion doesn't invoke .delete() on the cascaded objectsClarify that cascade deletion doesn't invoke .delete() on the cascaded objects
Triage Stage: UnreviewedAccepted
Type: UncategorizedCleanup/optimization

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.

comment:4 by Jacob Tomlinson, 6 years ago

Owner: changed from nobody to Jacob Tomlinson
Status: newassigned

comment:5 by Tim Graham <timograham@…>, 6 years ago

Resolution: fixed
Status: assignedclosed

In e038f98b:

Fixed #29398 -- Doc'd that cascade deletion doesn't call delete() of related models.

comment:6 by Tim Graham <timograham@…>, 6 years ago

In 452abf7:

[2.1.x] Fixed #29398 -- Doc'd that cascade deletion doesn't call delete() of related models.

Backport of e038f98bf342af716cf16e38be989c2d0f126797 from master

Note: See TracTickets for help on using tickets.
Back to Top