Django中apps.get_models()无法加载其他目录下模型的问题
问题:Django无法加载子目录中的模型文件
我的项目里有client、brand、reseller、company四个独立目录,每个目录下都包含models.py文件。使用apps.get_models()时,apps/<some_app_name>/models.py中的所有模型都能正常加载,但上述四个子目录下的models.py里的模型却无法被识别加载。
相关测试代码如下:
import pytest from django.apps import apps # Set managed=True for unmanaged models. !! Without this, tests will fail because tables won't be created in test db !! @pytest.fixture(autouse=True, scope="session") def __django_test_environment(django_test_environment): unmanaged_models = [m for m in apps.get_models() if not m._meta.managed] for m in unmanaged_models: m._meta.managed = True
当前环境:Python 3.9.18、Django 3.2.21。补充说明:这4个模型均继承自Account,Account继承自PolymorphicMPTTModel(支持复杂父子关系)。
请问应如何配置pytest或Django,使其能查找这些模型?
解决方案
要让Django识别这些子目录下的模型,需要做以下配置:
将子目录转为Django应用
Django默认只会识别INSTALLED_APPS里注册的应用中的模型,所以需要把client、brand、reseller、company这几个目录配置成独立的Django应用:- 在每个子目录下添加
apps.py文件,以client为例:# client/apps.py from django.apps import AppConfig class ClientConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'client' - 在每个子目录下添加空的
__init__.py文件,让Python将其识别为包。
- 在每个子目录下添加
在settings.py中注册这些应用
在项目的settings.py的INSTALLED_APPS中添加这些应用:INSTALLED_APPS = [ # 原有应用... 'client', 'brand', 'reseller', 'company', ]确保模型被正确导入
如果这些子目录的models.py没有被自动导入,需要在对应应用的__init__.py中导入models:
比如在client/__init__.py中添加:from .models import *针对pytest的额外检查
- 确保
pytest-django插件已正确安装(可通过pip install pytest-django安装)。 - 确认
pytest.ini中配置了正确的Django设置模块:[pytest] DJANGO_SETTINGS_MODULE = your_project.settings
- 确保
完成以上配置后,重新运行测试,apps.get_models()就能正确加载这些子目录下的模型了。
内容的提问来源于stack exchange,提问作者Vini.g.fer
相关产品推荐
相关产品推荐

