首页 > 解决方案 > __init__.py 中的自定义函数导致尚未安装 Django 应用程序错误

问题描述

我有如下设置

    Tasks
      |__ __init__.py
      |__ a.py
      |__ b.py
      |__ c.py
         ...

在 __init__.py 文件中,

    from .a import custom1, custom2
    from .b import custom3, custom4

我在任务中编写了一个函数,该函数需要将任务添加为 INSTALLED_APP。

然而,自定义函数会引发 django.core.exceptions.AppRegistryNotReady:“应用程序尚未加载。”。

回溯会导致其中一个自定义函数尝试导入

from django.contrib.auth.models import User.

为什么会发生这种情况,有没有办法在不将自定义函数移出 __init__.py 文件的情况下修复此错误?

标签: pythondjango

解决方案


Order of Django initialization is well documented

1.) First Django imports each item in INSTALLED_APPS.

At this stage, your code shouldn’t import any models!

...

3.)Finally Django runs the ready() method of each application configuration.

And futher as documented in AppConfig.ready()

Subclasses can override this method to perform initialization tasks such as registering signals. It is called as soon as the registry is fully populated.

class RockNRollConfig(AppConfig):
# ...

    def ready(self):
        # importing model classes
        from .models import MyModel  # or...
        MyModel = self.get_model('MyModel')

        # registering signals with the model's string label
        pre_save.connect(receiver, sender='app_label.MyModel')

You might consider use of get_model inside of your function that would replace import with require_ready false

But I am not certain it would work depending on your use case


推荐阅读