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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With