Django:ModelChoiceField 和 django.setup()
Django: ModelChoiceField and django.setup()
如果我尝试 运行 通过 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.
我在 运行 测试用例时遇到了同样的问题,并通过在开头使用 import 语句将其添加到测试文件中解决了这个问题
import os
import sys
from django.core.handlers.wsgi import WSGIHandler
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
application = WSGIHandler()
没有看到你的代码有点难说,但我曾经遇到过类似的问题。对我来说,它与我的模型正在导入的模块有关,并且还包含我的模型的导入。
ModelA --- 进口 --> 服务 -- 进口 --> ModelA
我通过将服务中的导入移动到需要导入的方法来解决这个问题。因此,我没有将它放在服务模块的顶部,而是将导入的范围限制为需要此导入的方法,从而避免在初始化服务模块时导入模型。 Fwew,我希望我能画给你:)
请显示您的确切代码(尤其是 extra()
子句)。在导入时调用 filter()
或 exclude()
还不错,因为查询集是惰性的,但您可以在此处评估导致异常的查询集。
不要在导入期间评估查询集,因为导入语句只执行一次:例如,如果创建了一个新组,它将无法作为您的 ModelChoiceField 选择。
您目前正在 运行 使用 PyCharm 的 Python 单元测试运行器 pycharm-4.5.1/helpers/pycharm/utrunner.py
进行测试。
这个测试运行器非常适合不涉及 ORM 等 Django 功能的低级单元测试(从 unittest.TestCase
子类化),但是
如果测试依赖于 Django 特定的东西,比如数据库,那么你的测试用例可能需要从 django.test.testcases.TestCase
继承下来,你需要通过 PyCharm 的 Django 测试管理器 django_test_manage.py
,负责设置测试数据库、初始化模型注册表等。
运行 > 编辑配置 > 添加新配置(+ 按钮)> Django 测试
将目标设置为 foo.foo.tests.FooEditTest
,如果找不到您的设置,请确保将 DJANGO_SETTINGS_MODULE=...
放入环境变量中。
如果我尝试 运行 通过 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.
我在 运行 测试用例时遇到了同样的问题,并通过在开头使用 import 语句将其添加到测试文件中解决了这个问题
import os
import sys
from django.core.handlers.wsgi import WSGIHandler
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
application = WSGIHandler()
没有看到你的代码有点难说,但我曾经遇到过类似的问题。对我来说,它与我的模型正在导入的模块有关,并且还包含我的模型的导入。
ModelA --- 进口 --> 服务 -- 进口 --> ModelA
我通过将服务中的导入移动到需要导入的方法来解决这个问题。因此,我没有将它放在服务模块的顶部,而是将导入的范围限制为需要此导入的方法,从而避免在初始化服务模块时导入模型。 Fwew,我希望我能画给你:)
请显示您的确切代码(尤其是 extra()
子句)。在导入时调用 filter()
或 exclude()
还不错,因为查询集是惰性的,但您可以在此处评估导致异常的查询集。
不要在导入期间评估查询集,因为导入语句只执行一次:例如,如果创建了一个新组,它将无法作为您的 ModelChoiceField 选择。
您目前正在 运行 使用 PyCharm 的 Python 单元测试运行器 pycharm-4.5.1/helpers/pycharm/utrunner.py
进行测试。
这个测试运行器非常适合不涉及 ORM 等 Django 功能的低级单元测试(从 unittest.TestCase
子类化),但是
如果测试依赖于 Django 特定的东西,比如数据库,那么你的测试用例可能需要从 django.test.testcases.TestCase
继承下来,你需要通过 PyCharm 的 Django 测试管理器 django_test_manage.py
,负责设置测试数据库、初始化模型注册表等。
运行 > 编辑配置 > 添加新配置(+ 按钮)> Django 测试
将目标设置为 foo.foo.tests.FooEditTest
,如果找不到您的设置,请确保将 DJANGO_SETTINGS_MODULE=...
放入环境变量中。