DatabaseRouter, add on runtime add new items to db.connections

261 views
Skip to first unread message

Matthieu Guffroy

unread,
Feb 23, 2017, 6:58:53 AM2/23/17
to Django users
Hello,

We are using in our system for more than 2 years now, a specific DatabaseRouter allowing us to use multiple databases depending on which clients is connecting.
It appears now, that the databases lists start to be really big, and that it becomes bad to be forced to re-deploy our backend to add a new database in the settings.

So we add the configurations in a specific database, and add to our middleware that was previously just setting the database to use in function of the request, the ability to load dynamically new database configurations.
With a function like this :

from django.db import connections
def add_db_connection(system_id, name, user, password, host, protocol):
    connections.databases[system_id] = {
        'ENGINE': 'django.db.backends.' + protocol,
        'NAME': name,
        'USER': user,
        'PASSWORD': password,
        'HOST': host,
        'CONN_MAX_AGE': 0
    }

It appears we don't seams to be firsts to edit dynamically this, as it is also the way works this extension : 
https://github.com/ambitioninc/django-dynamic-db-router

But before we put our new code in production, as we doesn't have found some clear indication about if we can or if we cannot edit django.db.connections in the documentation. We will be more confident, if someone involved in django development can give us it's feedback about this way of making things and if it's the recommended way ? or if their is a better way ?

Thanks a lot, for all you feedback,

Matthieu

Anton Melser

unread,
Sep 15, 2020, 9:45:10 AM9/15/20
to Django users
There appear to be relatively few references to this sort of thing peppered about the net, like this ancient stackoverflow post https://stackoverflow.com/questions/6585373/django-multiple-and-dynamic-databases, the below email, or the now long abandoned db router mentioned below. 

Is there a "why this is completely unsupported and we won't answer any questions about it" post from one of the Django Masters somewhere? I also really want to do this... (actually am doing it but the dynamic dbs aren't managed by django, and I would really like them to be...). If it is a reasonable thing to do, is there some place with good advice on how to go about it? Thanks!
Reply all
Reply to author
Forward
0 new messages