Search code examples
databasedjangoreloadon-the-fly

Possible to refresh Django connections on the fly?


Is it possible to add a new database connection to Django on the fly?

I have an application that uses multiple databases (django 1.2.1), and while running, it's allowed to create new databases. I'd need to use this new database right away (django.db.connections[db_alias]). Is it possible without server restart? Using module reload here and there?

Thank you for your time.


Solution

  • It is possible... but not recommended... You can access the current connection handler...

    Use something like this:

    from django.db import connections
    if not alias in connections.databases:
        connections.databases[alias] = connections.databases['default']  # Copy 'default'
        connections.databases[alias]['NAME'] = alias              
    

    Make sure you do not attempt to add a new alias to the databases dictionary while there is ANY database activity on the current thread.

    An issue you need to overcome, is that this code will need to be placed somewhere were it will always be touched by the current thread before trying to access the database. I use middleware to achieve this.