1

I am looking to find out when a connection is made to my Django database, or when my Django server is restarted. I found the connection_created Django signal. The description 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 I think using this signal will be a good solution for my case. I want to run a function once the connection is made. I can't find any documentations on the use cases of this signal. connection_created.connect is probably the function to use. This function takes in a bunch of arguments, but the ones that are relevant are self, receiver, sender and weak. Does anyone know how I can use these arguments and this function to run my function at a new connection instance?

Also if anyone has any alternative solutions other than this signal, I'd love to hear them.

guettli
  • 25,042
  • 81
  • 346
  • 663
cookiedough
  • 3,552
  • 2
  • 26
  • 51

2 Answers2

7

I have all my tables distributed among dynamic postgres table schemas, and use the connection signal to set the search path of the connection, since django does not support postgres schemas.

in myapp/apps.py

from django.db.backends.signals import connection_created

class MyappConfig(AppConfig):
    name = 'myapp'
    def ready(self):
        from myapp.schema_manager import new_connection
        connection_created.connect(new_connection)

in myapp/schema_manager.py

def new_connection(sender, connection, **kwargs):
    search_path = ['public'] + get_current_schemas()  # fetch the active schemas
    connection.cursor().execute("SET search_path TO %s;" % ', '.join(search_path)

According to the docs, this signal receives two arguments:

sender

The database wrapper class – i.e. django.db.backends.postgresql.DatabaseWrapper or django.db.backends.mysql.DatabaseWrapper, etc.

connection

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

Community
  • 1
  • 1
alfonso.kim
  • 2,844
  • 4
  • 32
  • 37
0

... since django does not support postgres schemas

Django supports postgres schemas:

class MyModel(models.Model):
    id = models.IntegerField(primary_key=True)
    title = models.TextField()

    class Meta:
        db_table = '"schema_name"."table_name"'

I use this notation in all of our projects.

Andy
  • 1
  • 1
  • 1