简体   繁体   中英

django dynamic (multiple) databases

My Django site is a portal for 1000's of customers, so I have a single "portal" database that has in the user table the connection parameters for a given customer. These are dynamic as they can be added and deleted from time to time so there is no way to just manage them out of the settings.py file.

So the "default" database is a local database that once the user is logged in certain apps need to make use of the given users database connection parameters to the backend server for that user.

I need those app models to dynamically use the connection settings that are in the user class.

I've looked at a number of solutions for multi-tenant, but these don't really fit.

I know I can decorate the model with a app_label and use a custom database router override the "default" settings entry, but I am not sure where to do from there.

I see I can write a post-authentication middleware that appends to settings.DATABASES but I believe I have read this is playing with fire.

Is there cleaner or more elegant way of handling this?

Use django.db.connections . It serves as a wrapper to the DATABASES defined in your SETTINGS . So maybe you can grab the db settings in your middleware somewhere then add a connection to your settings.

from django.db import connections

# Add connection information in middleware
connections.databases['new-alias'] = { ... }

# Use like this
Test.objects.using('new-alias').all()

Something like that should work. Doing it this way you'll only have the "portal" db defined in the settings.py file and each individual client DB is defined dynamically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM