How to execute code when Python Django starts once only?

To execute code when Python Django starts once only, we can put our code in the AppConfig class.

For instance, we write

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'myapp'
    verbose_name = "My Application"
    def ready(self):
        pass # startup code here

to create the MyAppConfig that inherits from the AppConfig class.

And we put our startup code in the ready method.

Then in myapp/__init__.py, we add

default_app_config = 'myapp.apps.MyAppConfig'

to set the default_app_config to the path to our MyAppConfig class in our app to make Django run it on startup.