在Django中调用delete()会给出错误消息

时间:2015-12-04 22:54:04

标签: python django

让我们说在Django我有模型:

class Test(models.Model):
    name = models.CharField(max_length = 100)

然后我在Django Shell中使用以下代码:

from app.models import Test
test = Test(name = "Hi")
test.save()

到目前为止一切顺利。现在我做:

Test.objects.all().delete()

然后我收到一条很长的错误消息:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Alexander\Anaconda3\lib\site-packages\django\db\models\query.py", line 536, in delete
    collector.collect(del_query)
  File "C:\Users\Alexander\Anaconda3\lib\site-packages\django\db\models\deletion.py", line 193, in collect
    if self.can_fast_delete(objs):
  File "C:\Users\Alexander\Anaconda3\lib\site-packages\django\db\models\deletion.py", line 155, in can_fast_delete
    for related in get_candidate_relations_to_delete(opts):
  File "C:\Users\Alexander\Anaconda3\lib\site-packages\django\db\models\deletion.py", line 67, in <genexpr>
    f for f in candidate_model_fields
  File "C:\Users\Alexander\Anaconda3\lib\site-packages\django\db\models\deletion.py", line 62, in <genexpr>
    opts.get_fields(include_hidden=True) for opts in candidate_models
  File "C:\Users\Alexander\Anaconda3\lib\site-packages\django\db\models\options.py", line 740, in get_fields
    return self._get_fields(include_parents=include_parents, include_hidden=include_hidden)
  File "C:\Users\Alexander\Anaconda3\lib\site-packages\django\db\models\options.py", line 802, in _get_fields
    all_fields = self._relation_tree
  File "C:\Users\Alexander\Anaconda3\lib\site-packages\django\utils\functional.py", line 59, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\Alexander\Anaconda3\lib\site-packages\django\db\models\options.py", line 709, in _relation_tree
    return self._populate_directed_relation_graph()
  File "C:\Users\Alexander\Anaconda3\lib\site-packages\django\db\models\options.py", line 681, in _populate_directed_relation_graph
    all_models = self.apps.get_models(include_auto_created=True)
  File "C:\Users\Alexander\Anaconda3\lib\site-packages\django\apps\registry.py", line 168, in get_models
    self.check_models_ready()
  File "C:\Users\Alexander\Anaconda3\lib\site-packages\django\apps\registry.py", line 131, in check_models_ready
    raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

我看到其他人收到类似的错误消息,但他们没有使用delete()操作,也没有使用Django shell。如果它是相关的,我在Microsoft Visual Studio 2015中使用Django 1.8.6。

1 个答案:

答案 0 :(得分:1)

从我见过的different SO answers,这将解决问题:

import django
django.setup()

背后的原因是

  

基本上,Django有一种新方法来加载已安装的应用程序。如果你加载   一些来自Python脚本的Django(就像我在我的自定义单元测试中)   初始化需要在继续并调用setup()之前完成   是怎么做的。除此之外,对团队的赞誉,我的1.6.2到1.7.1   升级似乎需要一个小时的实际工作。

     

- JL Peyret