Django: running code on every startup but after database is migrated

后端 未结 1 1777
猫巷女王i
猫巷女王i 2021-02-20 04:42

I thought there was an easy answer to this in recent versions of Django but I can\'t find it.

I have code that touches the database. I want it to run every time Django s

1条回答
  •  自闭症患者
    2021-02-20 05:21

    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)
    

    0 讨论(0)
提交回复
热议问题