[Fixed]-Django: running code on every startup but after database is migrated

4👍

I would suggest the connection_created signal, which is:

Sent when the database wrapper makes the initial connection to the
database. This is particularly useful if you’d like to send any post
connection commands to the SQL backend.

So it will execute the signal’s code when the app connects to the database at the start of the application’s cycle.

It will also work within a multiple database configuration and even separate the connections made by the app at initialization:

connection
The database connection that was opened. This can be used in a multiple-database configuration to differentiate connection signals
from different databases.


Note:
You may want to consider using a combination of post_migrate and connection_created signals while checking inside your AppConfig.ready() if a migration happened (ex. flag the activation of a post_migrate signal):

from django.apps import AppConfig
from django.db.models.signals import post_migrate, connection_created
# OR for Django 2.0+
# django.db.backends.signals import post_migrate, connection_created

migration_happened = false

def post_migration_callback(sender, **kwargs):
    ...
    migration_happened = true


def init_my_app(sender, connection):
    ...


class MyAppConfig(AppConfig):
    ...

    def ready(self):
        post_migrate.connect(post_migration_callback, sender=self)

        if !migration_happened:
            connection_created.connect(init_my_app, sender=self)

1👍

In Django >= 3.2 the post_migrate signal is sent even if no migrations are run, so you can use it to run startup code that talks to the database.

https://docs.djangoproject.com/en/3.2/ref/signals/#post-migrate

Sent at the end of the migrate (even if no migrations are run) and flush commands. It’s not emitted for applications that lack a models module.

Handlers of this signal must not perform database schema alterations as doing so may cause the flush command to fail if it runs during the migrate command.

Leave a comment