Django model: objects.all (). delete () does not

I am trying to clear and reload a table in my django model and

>>> models.PuzzleSum.objects.all().count() 2644 >>> models.PuzzleSum.objects.all().delete() >>> models.PuzzleSum.objects.all().count() 2535 

... wtf? It's always a magic number 109. I know that I can just go into the database and delete them manually (or a loop until they disappear), but I'm curious.

(Django 1.3.1 on Mac OS X Lion btw)

+6
source share
2 answers

Yes, Django stores all objects in a dict, and then deletes them one at a time. This is the reason why only unique elements are deleted because they iterate over them. This is from the Django Collector class, which collects models for removal:

 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 override __hash__ your models, when the models are stored in the self.data file, only unique ones are saved and then deleted.

+2
source

Converting my comment above to the question:

I have an overridden hash and eq in PuzzleSum due to the specific definition of "duplicate" that I want to use. And guess what: I have 109 different hash values. Django should use a collection of objects somewhere inside its delete logic.

0
source

Source: https://habr.com/ru/post/921712/


All Articles