Opened 9 years ago

Closed 9 years ago

Last modified 9 years ago

#12034 closed (wontfix)

Deleting an model instance doesn't call the delete() method of related instances (even though they are removed).

Reported by: Ilya Owned by: nobody
Component: Database layer (models, ORM) Version: 1.1
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


Do not calling delete method of models, when remove related objects.


from django.db import models

class myModel1(models.Model):

	def delete(self):
		print "Delete myModel1 called"
		super(myModel1, self).delete()

class myModel2(models.Model):
	m = models.ForeignKey(myModel1)

	def delete(self):
		print "Delete myModel2 called"
		super(myModel2, self).delete()

>>> a = myModel1()
>>> b = myModel2(m = a)
>>> a.delete()
Delete myModel1 called
>>> myModel2.objects.all()

Object of myModel2 class deleted, but method myModel2.delete not called.

Change History (4)

comment:1 Changed 9 years ago by Chris Beaven

Component: UncategorizedDatabase layer (models, ORM)
Resolution: wontfix
Status: newclosed
Summary: Do not calling delete() method of models, when remove related objectsDeleting an model instance doesn't call the delete() method of related instances (even though they are removed).

The delete() methods of related instances are not called because it would be highly inefficient (every related model would have to be instanciated).

If you want to ensure your pre/post delete actions are run, you should be using the pre_delete or post_delete signals.

comment:2 Changed 9 years ago by Ilya

Mmm, django actually call for every related model pre_delete and post_delete signals. So calling some function for every related models was found not inefficient.
And I think, that not calling delete() method leads to destroy the integrity of data.
For example: we have model myModel with FileField. In case, when we call delete() from some of myModel's object, this object and related file will be deleted.
If we call delete of related to myModel's object, this object will be deleted, but file will remain.

comment:3 Changed 9 years ago by Chris Beaven

Ok, you're actually correct that Django instanciates every related object it's going to delete. Calling delete on all of these methods would still be highly inefficient because it would be a SQL call for each instance.

You are incorrect about your "integrity of data" example. The FileField adds a delete signal to delete the related file, it doesn't attach itself to the delete method.

comment:4 Changed 9 years ago by cgieringer

Related: #6870

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