We did it! Let me explain how.
We wrote custom middleware and registered it as a middleware class inside our settings.py file.
MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'our.custom.middleware.Class', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', )
This middleware has a process_request method that creates a thread variable ( from threading import local ) to store the corresponding database name for the current user.As each request is processed by a different thread, we know that our variable value will not be accidentally changed by another thread.
The next step was to create a Database Router and register it as such.
DATABASE_ROUTERS = ('our.custom.database.Router',)
Note: by default, settings.py does not have the DATABASE_ROUTERS variable. You will need to create it.
Our custom Router has the same features for db_for_read and db_for_write . The only thing these methods do is to return the database name stored in our stream variable.
What is it. Now we do not need to call using every time we need to restore or save model objects.
source share