问题描述
在Django启动时,我需要运行一些需要访问数据库的代码。我更喜欢通过模型来做到这一点。
On Django startup I need to run some code that requires access to the database. I prefer to do this via models.
这是我目前在 apps.py
中所拥有的:
Here's what I currently have in 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
但是,这给出了以下异常:
However, this gives the following exception:
django.core.exceptions.AppRegistryNotReady:应用尚未加载。
那么,在模型初始化之后,Django中是否有地方可以运行一些启动代码?
So is there a place in Django to run some startup code after the models are initialized?
推荐答案
问题是您导入了 .models
在文件顶部。这意味着,当加载文件 app.py
时,Python会在加载 models.py
文件时加载它评估那条线。但这还太早了。您应该让Django正确执行加载。
The problem is that you import .models
at the top of your file. This means that, when the file app.py
file is loaded, Python will load the models.py
file when it evalutes that line. But that is too early. You should let Django do the loading properly.
您可以在 def ready(self)
方法中移动导入,这样在Django框架调用 ready()
时,会导入 models.py
文件,例如:
You can move the import in the def ready(self)
method, such that the models.py
file is imported when ready()
is called by the Django framework, like:
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
这篇关于在Django中我可以在哪里运行需要模型的启动代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!