基于当前用户登录的Django数据库路由

时间:2016-09-06 17:28:31

标签: django python-3.x django-rest-framework

view课程中,您可以调用self.request.user并根据该操作执行操作。在我的情况下,我希望能够根据当前登录的用户切换数据库。无论如何,要在self.requestdb_for_read()方法中注入db_for_write()调用,例如以下

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"

3 个答案:

答案 0 :(得分:3)

您可以使用RouterMiddlewear检查用户是否已登录,然后将所有queries重定向到您选择的特定数据库,如果您使用{{1执行查询。

view based

以下是我根据您的要求修改的link

确保将class RouterMiddleware (object): def process_view( self, request, view_func, args, kwargs ): # Check the user logged in user = self.request.user # Call your functions to set the database by passing the user.id def process_response( self, request, response ): # Make the database to default here if you wish to use it no longer return response class DataBaseRouter(object): def db_for_read(self, model, user_id=None, **hints): if user.id == 1: return "master" return "default" def db_for_write(self, model, user_id=None, **hints): if user.id == 1: return "master" return "default" 添加到RouterMiddleware

答案 1 :(得分:1)

试试这个django dynamic db router package。它非常简单。安装它并配置和使用如下。

<强> 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)

答案 2 :(得分:0)

为解决此问题,我创建了一个只有一个userid字段的新模型。然后在路由器中指定用于读取和写入的db时,我从该模型中获取数据,因此不需要任何请求参数。
而且我只是在基本模板中添加了一个简短的Ajax代码,因此无论何时打开我的网站,它都会从request.user获取用户ID并更改模型行,以便当前用户ID像这样更改。