python - Django 测试模型根据它们的位置加载?

标签 python django testing python-import

我有一个具有以下结构的 Django 应用程序:

app/
    tests/
        __init__.py
        tests.py
    __init__.py
    test_model.py

tests.py 中,我像这样导入测试模型:from app.test_model import *。这按预期工作:在测试期间,模型被加载,它们对应的数据库表被创建等等。

但是,如果我将 test_model.py 文件移动到 tests/ 目录中:

app/
    tests/
        __init__.py
        test_model.py
        tests.py
    __init__.py

并进行相应的导入:from app.tests.test_model import *,它突然失败了。未检测到模型,因此未创建它们的数据库表并且测试开始失败(DatabaseError:没有这样的表:app_model)。

为什么会这样?我应该如何避免这种情况并仍然将 test_model.py 文件放在 tests/ 中?

最佳答案

我假设 test_models.py 实际上是您创建所有模型的地方。 Django 查找模型应用程序名称作为父文件夹,并按照您的方式嵌套它可能会导致它在查找应用程序名称时卡住。我不完全了解这里的机制,但我以前经历过。简单的解决方案是使用 Meta option 手动指定应用程序:

class MyModel(Model):

    ...

    class Meta:
        app_label = 'app'

关于python - Django 测试模型根据它们的位置加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21187315/

相关文章:

python - 使用 sum 函数时遇到问题

python - 在注释中组合 F 和 Count 时,Django "Unknown column in having clause"

python - 子域和登录

unit-testing - 如何使用 Testng 并行运行测试?

laravel - 如何将 Laravel 队列工作限制在一个执行结束导出?

.net - 如何对 Response.Redirect 进行单元测试?

python - 如何从另一个Docker容器连接Postgres Docker镜像

python - Redshift + SQLAlchemy 长查询挂起

python /杰森 : If substring in string always results in TypeError: string member test needs char left operand

html - 使用 Django 提交表单时,如何使用 html 元素的 CSS 属性值作为输入?