django model: objects.all().delete() doesn't

I am trying to clear out 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? Always the magic number 109. I know I could just go into the database and delete them by hand (or loop until they're all gone) but I'm curious.

(Django 1.3.1 on Mac OS X Lion btw)


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.


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.

链接地址: http://www.djcxy.com/p/62104.html

上一篇: Node,Express,Ajax和Jade示例

下一篇: django模型:objects.all()。delete()不