Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 731
AlanL Avatar asked Jul 30 '12 18:07

AlanL


People also ask

What does objects all () return in Django?

all() Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result. After calling all() on either object, you'll definitely have a QuerySet to work with.

How do I delete a specific record in Django?

To delete a record we do not need a new template, but we need to make some changes to the members template. Of course, you can chose how you want to add a delete button, but in this example, we will add a "delete" link for each record in a new table column. The "delete" link will also contain the ID of each record.

What is soft delete in Django?

Soft Delete Model This means that Django will not create a database table for it. Now, we can create our models as subclasses of SoftDeleteModel to grant them the ability to be soft-deleted. Let's take the example of a Note model. class Note(SoftDeleteModel): user = models. ForeignKey(User, on_delete=models.


1 Answers

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.

like image 167
Tisho Avatar answered Sep 27 '22 19:09

Tisho