[Fixed]-Where in Django can I run startup code that requires models?

18👍

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

Leave a comment