Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 483
Serge Rogatch Avatar asked Jan 05 '19 20:01

Serge Rogatch


People also ask

Where are Django models stored?

Django models inside apps in the models folder. The first technique to store Django models outside of models.py files is to create a folder named models -- inside the same app -- declare class models in standalone files in this folder and import the classes through this new folder's __init__ file.

Which file runs first in Django?

The First line will create a migration file by Django which are basically commands on how to convert the model into a database table. The Second line will execute the commands and creates a table called User with the given attributes and conditions.


1 Answers

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
like image 91
Willem Van Onsem Avatar answered Sep 22 '22 21:09

Willem Van Onsem