Django App 初始化流程(论细读文档的重要性)
在我们的大型Django项目中,需要在服务启动后枚举出系统所有的models类。
然而在 app
的 ready()
方法中总是无法获取到某些model类,一直怀疑是初始化还不完全,直到看见了Django的文档:
https://docs.djangoproject.com/en/4.1/ref/applications/#initialization-process
The application registry is initialized in three stages. At each stage, Django processes all applications in the order of INSTALLED_APPS.
First Django imports each item in INSTALLED_APPS.
If it’s an application configuration class, Django imports the root package of the application, defined by its name attribute. If it’s a Python package, Django looks for an application configuration in an apps.py submodule, or else creates a default application configuration.
At this stage, your code shouldn’t import any models!
In other words, your applications’ root packages and the modules that define your application configuration classes shouldn’t import any models, even indirectly.
Strictly speaking, Django allows importing models once their application configuration is loaded. However, in order to avoid needless constraints on the order of INSTALLED_APPS, it’s strongly recommended not import any models at this stage.
Once this stage completes, APIs that operate on application configurations such as get_app_config() become usable.
Then Django attempts to import the models submodule of each application, if there is one.
You must define or import all models in your application’s models.py or models/_init_.py. Otherwise, the application registry may not be fully populated at this point, which could cause the ORM to malfunction.
Once this stage completes, APIs that operate on models such as get_model() become usable.
Finally Django runs the ready() method of each application configuration.
所以根据文档的描述,Django会试图加载 models.py
和 models/__init__.py
文件中的model类。
而找不到的那几个model类不在这两个位置,导致django不会默认进行加载。