[Solved]-Django model: objects.all().delete() doesn't

6👍

Yes, Django is storing all objects in a dict, and then deletes them one by one. That’s the reason why only the unique items are deleted, as it iterates over them. This is from the Django Collector class, which collects the models for deletion:

self.data = SortedDict([(model, self.data[model])
                        for model in sorted_models])

and then:

# delete instances
for model, instances in self.data.iteritems():
    query = sql.DeleteQuery(model)
    pk_list = [obj.pk for obj in instances]
    query.delete_batch(pk_list, self.using)

As long as you’ve overridden the __hash__ of your models, when the models are stored in the self.data dict, only the unique ones are stored, and then deleted.

👤Tisho

2👍

Converting my comment above into an answer to the question:

I have overridden hash and eq in PuzzleSum because of a particular definition of “duplicate” that I want to use. And guess what: I have 109 distinct hash values. Django must be using a set of objects somewhere internally in its delete logic.

👤AlanL

Leave a comment