在Django中我可以在哪里运行需要模型的启动代码?

时间:2019-01-05 20:08:55

标签: python django database django-models startup

在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中是否有地方可以运行一些启动代码?

1 个答案:

答案 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