In a view
class, you could call self.request.user
and perform actions based on that. In my case, I would like to be able to switch databases depending on the current user logged in. Is there anyway to inject a self.request
call into the db_for_read()
and db_for_write()
methods like in the following?
class DataBaseRouter(object):
def db_for_read(self, model, **hints):
user = self.request.user
if user.id == 1:
return "master"
return "default"
def db_for_write(self, model, **hints):
user = self.request.user
if user.id == 1:
return "master"
return "default"
You can use a
RouterMiddlewear
to check if what user is logged in and then redirect all thequeries
to a particular database of your choice, this would be help full if you are usingview based
execution of the queries.Here is the link that I have modified for your requirement.
Make sure you add the the
RouterMiddleware
to yourMIDDLEWARE_CLASSES
.Try this django dynamic db router package. its very simple. install it and configure and use as below.
settings.py
my_app/views.py