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 depend
Try this django dynamic db router package. its very simple. install it and configure and use as below.
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'my_local_database',
'USER': 'postgres',
'PASSWORD': 'my-pass',
'HOST': '127.0.0.1',
'PORT': '5432',
},
'master': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'my_master_database',
'USER': 'postgres',
'PASSWORD': 'my-pass',
'HOST': 'example.com',
'PORT': '5432',
},
}
DATABASE_ROUTERS = ['dynamic_db_router.DynamicDbRouter']
my_app/views.py
from dynamic_db_router import in_database
from my_app.models import MyModel
def index(request):
#Picking the DB based on logged in user or you can do this in middile ware as well.
use_db = "default"
user = self.request.user
if user.id == 1:
use_db = "master"
# Fetching data from selected databases.
with in_database(use_db):
input = MyModel.objects.filter(field_a="okay")
output = complex_query_function(input)