python - __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 文件的情况下修复此错误?
解决方案
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
推荐阅读
- flutter - “_drawAreaBoundsOutdated == false': is not true”使用 charts_flutter 包更新 TimeSeriesChart 的列表数据时出错
- amazon-web-services - Glue Classifier 无法使用 Grok 模式对列进行分类
- mybatis - MyBatis:无效比较:java.util.Date 和 java.lang.String
- python - 在外部库中使用时禁用 tensorflow 日志
- javascript - [{a: 1}],[{b: 2}] 转换为 {a:1,b:2}
- python - Pandas get cell value by row NUMBER (NOT row index) and column NAME
- sql - Oracle 10g 和 11g 中的 Regexp_like
- c - 传递 'atoi' 的参数 1 从整数中生成指针,而无需在 C 中进行强制转换
- sequelize.js - 是否可以使用 sequelize 中的钩子获取插入行的 ID?
- java - 缺少return语句,但是return语句在那里?