django model:objects.all()。delete()不 [英] django model: objects.all().delete() doesn't

查看:856
本文介绍了django model:objects.all()。delete()不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试清除并重新加载我的django模型中的表,并且

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

...跆拳道?永远是魔术数字109.我知道我可以进入数据库并手动删除它们(或循环,直到它们都消失),但我很好奇。



(Django 1.3.1在Mac OS X Lion btw)

解决方案

是的,Django将所有对象存储在dict中,然后逐个删除它们。这就是为什么只有唯一的项目被删除,因为它重复它们。这是来自Django 收藏者类,其中收集要删除的模型:

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

然后:

 #delete examples 
for model,self.data.iteritems()中的实例:
query = sql.DeleteQuery(model)
pk_list = [obj.pk for obj in instance]
query.delete_batch(pk_list,self.using)

只要您覆盖了模型的 __ hash __ ,当模型存储在self.data dict中时,只存储唯一的模型,然后删除。


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.

这篇关于django model:objects.all()。delete()不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆