Where in Django can I run startup code that requir

2020-08-17 05:56发布

问题:

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