在Django启动时,我需要运行一些需要访问数据库的代码。我更喜欢通过模型来做到这一点。
这是我目前在apps.py
中所拥有的:
from django.apps import AppConfig
from .models import KnowledgeBase
class Pqawv1Config(AppConfig):
name = 'pqawV1'
def ready(self):
to_load = KnowledgeBase.objects.order_by('-timestamp').first()
# Here should go the file loading code
但是,这给出了以下异常:
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
在模型初始化之后,Django中是否有地方可以运行一些启动代码?
答案 0 :(得分:2)
问题是您在文件顶部导入了.models
。这意味着,当加载文件app.py
时,Python将在评估该行时加载models.py
文件。但这还太早了。您应该让Django正确执行加载。
您可以在def ready(self)
方法中移动导入,以便在Django框架调用models.py
时导入ready()
文件,例如:
from django.apps import AppConfig
class Pqawv1Config(AppConfig):
name = 'pqawV1'
def ready(self):
from .models import KnowledgeBase
to_load = KnowledgeBase.objects.order_by('-timestamp').first()
# Here should go the file loading code