Ser*_*tch 11 python database django startup django-models
在 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
Run Code Online (Sandbox Code Playgroud)
但是,这会导致以下异常:
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
那么在模型初始化之后,Django 中有没有地方可以运行一些启动代码呢?
Wil*_*sem 13
问题是您.models在文件顶部导入。这意味着,当app.py加载models.py文件 file 时,Python 将在评估该行时加载该文件。但这还为时过早。您应该让 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 codeRun Code Online (Sandbox Code Playgroud)