Django:ModelChoiceField和django.setup()

时间:2015-08-24 14:06:42

标签: python django django-settings

如果我尝试通过PyCharm运行测试,我会得到此异常

...bin/python /usr/local/pycharm-4.5.1/helpers/pycharm/utrunner.py ...src/foo/foo/tests/FooEditTest.py::FooEditTest::test_issue_add true
Testing started at 15:59 ...
Traceback (most recent call last):
  File "/usr/local/pycharm-4.5.1/helpers/pycharm/utrunner.py", line 139, in <module>
    module = loadSource(a[0])
  File "/usr/local/pycharm-4.5.1/helpers/pycharm/utrunner.py", line 41, in loadSource
    module = imp.load_source(moduleName, fileName)
  File "...src/foo/foo/tests/FooEditTest.py", line 45, in <module>
    from foo.views.issue.forward import forward
  File "...src/foo/foo/views/issue/forward.py", line 29, in <module>
    class ForwardForm(forms.Form):
  File "...src/foo/foo/views/issue/forward.py", line 36, in ForwardForm
    group=forms.ModelChoiceField(Group.objects.exclude(groupconfig__no_issue=True).extra(
  File "...python2.7/site-packages/django/db/models/manager.py", line 92, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "...python2.7/site-packages/django/db/models/query.py", line 698, in exclude
    return self._filter_or_exclude(True, *args, **kwargs)
  File "...python2.7/site-packages/django/db/models/query.py", line 707, in _filter_or_exclude
    clone.query.add_q(~Q(*args, **kwargs))
  File "...python2.7/site-packages/django/db/models/sql/query.py", line 1331, in add_q
    clause, require_inner = self._add_q(where_part, self.used_aliases)
  File "...python2.7/site-packages/django/db/models/sql/query.py", line 1358, in _add_q
    current_negated=current_negated, connector=connector)
  File "...python2.7/site-packages/django/db/models/sql/query.py", line 1182, in build_filter
    lookups, parts, reffed_aggregate = self.solve_lookup_type(arg)
  File "...python2.7/site-packages/django/db/models/sql/query.py", line 1120, in solve_lookup_type
    _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
  File "...python2.7/site-packages/django/db/models/sql/query.py", line 1383, in names_to_path
    field, model, direct, m2m = opts.get_field_by_name(name)
  File "...python2.7/site-packages/django/db/models/options.py", line 416, in get_field_by_name
    cache = self.init_name_map()
  File "...python2.7/site-packages/django/db/models/options.py", line 445, in init_name_map
    for f, model in self.get_all_related_m2m_objects_with_model():
  File "...python2.7/site-packages/django/db/models/options.py", line 563, in get_all_related_m2m_objects_with_model
    cache = self._fill_related_many_to_many_cache()
  File "...python2.7/site-packages/django/db/models/options.py", line 577, in _fill_related_many_to_many_cache
    for klass in self.apps.get_models():
  File "...python2.7/site-packages/django/utils/lru_cache.py", line 101, in wrapper
    result = user_function(*args, **kwds)
  File "...python2.7/site-packages/django/apps/registry.py", line 168, in get_models
    self.check_models_ready()
  File "...python2.7/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.

Process finished with exit code 1

我使用group=forms.ModelChoiceField(Group.objects.exclude(...)) 该行在导入期间执行。以前没有调用django.setup()

我不知道如何解决这个问题:

  • 我应该致电django.setup()吗?但是在哪里插入这条线?
  • 在导入时间内避免使用MyModel.objects.filter(...)?这需要大量重构,因为我们有几个ModelChoiceField s。

4 个答案:

答案 0 :(得分:2)

我在运行测试用例时遇到了同样的问题,并通过在导入语句的开头将其添加到测试文件来解决它

import os
import sys

from django.core.handlers.wsgi import WSGIHandler

os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
application = WSGIHandler()

答案 1 :(得分:2)

您目前正在使用PyCharm的Python单元测试运行器pycharm-4.5.1/helpers/pycharm/utrunner.py运行测试。 这个测试运行器非常适合低级单元测试(从unittest.TestCase继承)不能触及像ORM这样的Django功能,但是 如果测试依赖于Django特定的东西,比如数据库,那么你的TestCase可能需要从django.test.testcases.TestCase进行子类化,你需要通过PyCharm的Django测试经理django_test_manage.py ,负责设置测试数据库,初始化模型注册表等。

运行&gt;编辑配置&gt;添加新配置(+按钮)&gt; Django测试

将目标设置为foo.foo.tests.FooEditTest,如果找不到您的设置,请确保将DJANGO_SETTINGS_MODULE=...放入环境变量中。

答案 2 :(得分:1)

请显示您的确切代码(尤其是extra()子句)。在导入时调用filter()exclude()并不错,因为查询集很懒,但您可以在此处评估导致异常的查询集。

在导入时不要评估查询集,因为import语句只执行一次:例如,如果创建了一个新组,它将无法作为ModelChoiceField的选项。

答案 3 :(得分:0)

如果没有看到您的代码,有点难以说,但我有一次类似的问题。对我而言,它与我的模型导入的模块有关,并且还包含我的模型的导入。

ModelA --- 导入 - &gt; 服务 - 导入 - &gt;的 MODELA

我通过将我的服务中的导入移动到需要导入的方法来解决这个问题。因此,我没有将其放在服务模块的顶部,而是将导入范围限制为需要此导入的方法,从而避免在初始化服务模块时导入模型。 Fwew,我希望我能为你画画:)