Django Database Routing using USER from request

I am trying to implement a PER USER database routing in Django and things are not going that smoothly.

Databases are predefined and they have identical structure.

This is what I have right now and IT WORKS but I was wondering if there is anything better for what I want :

class DatabaseMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        
        if (str(request.company) == 'company1'):
            request.database="COMPANY_X"
        else:
            request.database="default"
            
        response = self.get_response(request)

        return response
    
    
 #THIS HAS SECURITY RISKS BUT I DONT THINK THERE IS SOMETHING BETTER OUT THERE FOR NOW
from threadlocals.threadlocals import get_current_request
class UserDatabaseRouter:
    def db_for_read(self, model,user_id=None, **hints):
        
        request = get_current_request()
        
        if(not (request is None)):
            return request.database
        else:
            return None
    
    def db_for_write(self, model,user_id=None, **hints):

        request = get_current_request()
        
        if(not (request is None)):
            return request.database
        else:
            return None

  • 1

    Do you want to set up connection to predefined database (or databases) for each user separately or you want to create database for each user on demand?

    – 

  • @sudden_appearance good catch , I edited the post . Every database is predefined and there is not need for dynamic database creation

    – 

Leave a Comment