How to dynamically switch databases for multi-tenancy in Django without modifying core settings?

I’m working on implementing multi-tenancy for a Django application, where each tenant will have a separate database. I create the databases dynamically when a new tenant is created and need to switch to the tenant's database for each request. Since the databases are created on the fly, I cannot register them in the settings.py file.

To achieve this, I plan to create middleware that intercepts the request, checks for the authenticated user, retrieves the appropriate database for that user, and dynamically switches to it for the request. However, I'm unsure about how to correctly implement this in Django, given its default database handling behavior. I need guidance on:

  1. Where to modify the code: What files or areas of Django need to be adjusted to make this work?
  2. Database switching: How do I properly switch to a dynamically created database per user without affecting other requests?
  3. Database routers: How do I use database routers to manage connections dynamically in my custom setup?
  4. Considerations for querysets and operations: What should I keep in mind when querying data or performing operations on the dynamically selected database?

I’m looking for a solution that doesn’t require me to modify the core application heavily and would allow me to switch databases smoothly based on the authenticated user for each request.

I’ve implemented middleware to dynamically switch the database based on the authenticated user. I used a custom function to retrieve the database connection name and modified it to use the user’s database. I also create new databases for tenants on the fly, but I’m not sure where else I need to make changes for this to work seamlessly in Django. I expected the application to switch to the tenant’s database upon authentication, but the switching logic isn’t behaving as expected for certain operations.

Вернуться на верх