以下是我的做法:
apps
文件夹中。sys.path.append(os.path.join(BASE_DIR, 'apps'))
声明之前)中添加了INSTALLED_APPS
,因此在导入我的应用时,我不需要指定apps
文件夹。apps.py
个文件以设置name = apps.myappname
INSTALLED_APPS
仍然使用myappname
(不是apps.myappname
)这是我到目前为止的内容:
单位测试,在整个运行时,在某个执行点失败时会出现如下错误:
ImportError: Failed to import test module: apps.badges.tests
Traceback (most recent call last):
File "/usr/lib/python3.6/unittest/loader.py", line 428, in _find_test_path
module = self._get_module_from_name(name)
File "/usr/lib/python3.6/unittest/loader.py", line 369, in _get_module_from_name
__import__(name)
File "/vagrant/fugo/fugoproj/apps/badges/tests.py", line 10, in <module>
from .factories import BadgeFactory
File "/vagrant/fugo/fugoproj/apps/badges/factories.py", line 6, in <module>
from .models import Badge
File "/vagrant/fugo/fugoproj/apps/badges/models.py", line 51, in <module>
models.Model):
File "/home/ubuntu/fenv/lib/python3.6/site-packages/django/db/models/base.py", line 118, in __new__
"INSTALLED_APPS." % (module, name)
RuntimeError: Model class apps.badges.models.Badge doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
以下是错误的徽章/ factories.py 文件:
from datetime import timedelta
import factory
from django.utils import timezone
from .models import Badge
# some code
在每个失败的测试中,它似乎与模型的相对导入相关(from .models import SomeModel
)。如果我用from myappname.models import SomeModel
替换它,这将解决错误。
我的代码中有什么问题吗?我想保留我的相对进口。
如何解释它不会因应用程序运行测试app而失败?
感谢。