Django Database routing based on current user logged in

后端 未结 3 2026
悲哀的现实
悲哀的现实 2020-12-11 08:39

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

3条回答
  •  再見小時候
    2020-12-11 09:22

    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)
    

提交回复
热议问题