Recently, I was building django-single-instance-model
. The package ensures that at all times there is exactly one instance of a model.
One of the tasks for building this package was ensuring that an instance of the model existed.
I wanted to run this code as early as possible, once the database connection had been made.
How did I do it?
In the __init__.py
of the main app, I hooked into the connection_created
signal. Here's how:
from django.dispatch import receiver
from django.db.backends.signals import connection_created
@receiver(connection_created)
def my_receiver(connection, **kwargs):
with connection.cursor() as cursor:
pass # your startup code here
Hope this helps you in the future! Follow me for more Django / Python tips!
Top comments (1)
great tip, thanks!