pythondjango

Can't create objects on start


I created a function and want to run it automatically on start. The function creates several objects

I have an error AppRegistryNotReady("Apps aren't loaded yet.") Reason is clear - the function imports objects from another application (parser_app)

I am starting app like this gunicorn --bind 0.0.0.0:8000 core_app.wsgi

# project/core_app/wsgi.py

import os

from django.core.wsgi import get_wsgi_application
from django.core.management import call_command
from scripts.create_schedules import create_cron_templates

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core_app.settings')

application = get_wsgi_application()
call_command("migrate")
call_command("collectstatic", interactive=False)
create_cron_templates()

Full error:

django_1         |   File "/project/core_app/wsgi.py", line 14, in <module>
django_1         |     from scripts.create_schedules import create_cron_templates
django_1         |   File "/project/scripts/create_schedules.py", line 1, in <module>
django_1         |     from parser_app.models import Schedule
django_1         |   File "/project/parser_app/models.py", line 7, in <module>
django_1         |     class TimeBase(models.Model):
django_1         |   File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 127, in __new__
django_1         |     app_config = apps.get_containing_app_config(module)
django_1         |   File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 260, in get_containing_app_config
django_1         |     self.check_apps_ready()
django_1         |   File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 138, in check_apps_ready
django_1         |     raise AppRegistryNotReady("Apps aren't loaded yet.")
django_1         | django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

Code of the function

# project/scripts/create_schedules.py

from parser_app.models import Schedule


def create_cron_templates():
    Schedule.objects.get_or_create(
        name="1",
        cron="0 9-18/3 * * 1-5#0 19-23/2,0-8/2 * * 1-5#0 */5 * * 6-7"
    )

Solution

  • Solved with help of ready() function in apps.py

    My solution

    class ParserAppConfig(AppConfig):
        default_auto_field = 'django.db.models.BigAutoField'
        name = 'parser_app'
    
        def ready(self):
            from scripts.create_schedules import create_cron_templates
    
            create_cron_templates()