Where in Django can I run startup code that requires models?

送分小仙女□ 提交于 2019-12-10 18:41:34

问题


On Django startup I need to run some code that requires access to the database. I prefer to do this via models.

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: Apps aren't loaded yet.

So is there a place in Django to run some startup code after the models are initialized?


回答1:


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.

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


来源:https://stackoverflow.com/questions/54055815/where-in-django-can-i-run-startup-code-that-requires-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!