将用户分配到特定数据库中的组

问题描述 投票:0回答:2

有谁知道如何将用户分配到组(到特定数据库)?

我知道如何读取/创建特定数据库的记录,但不太确定如何创建特定数据库的相关表记录。而且 Django 官方文档对此也不是很清楚。这种情况下的语法是什么?

from django.contrib.auth.models import User
from django.contrib.auth.models import Group

user = User.objects.using('db').get(pk=1) 
admin_group = Group.objects.using('db').get(name='admin') 
# Below line does not work. 
user.groups.add(admin_group)

最后一行似乎并没有真正为 auth_user_groups 表创建任何记录。相反,它会创建记录到默认数据库。如何在最后一行指定数据库?

sql django database model
2个回答
0
投票

在 Django 中,要将用户分配到特定数据库中的特定组,您可以使用 using 方法来指定数据库。您提供的代码几乎是正确的。以下是将用户分配给特定数据库中的特定组的语法:

from django.contrib.auth.models import User
from django.contrib.auth.models import Group

user = User.objects.using('db').get(pk=1)  # Get the user from the specific database 'db'
admin_group = Group.objects.using('db').get(name='admin')  # Get the group from the same database 'db'

# Assign the user to the group within the specified database
user.groups.add(admin_group)

这里要记住的关键点是 using('db') 方法同时用于 User 对象和 Group 对象,确保您从同一指定数据库 'db' 检索用户和组。

user.groups.add(admin_group) 行将用户添加到指定组。通过在 User.objects.using('db') 上下文中使用此行,它可以在指定的数据库上执行此操作。

确保在 Django 设置中正确配置了引用的数据库(在本例中为“db”),以确保在目标数据库上执行数据操作。


0
投票

只是为了确认上面的代码有效,但我有一个自定义数据库路由来更改 Django 的默认行为。

我最终如下更改了 db_for_write 以指定选择哪个数据库。我注意到在执行 user.groups.add(admin_group) 时,db_for_write 函数被调用,我从 **hint 中查找正确的数据库名称,这是所需的数据库。

def db_for_write(self, model, **hints):
        
        if hints.get('instance') is not None:
          _instance = hints['instance']
          return _instance._state.db
        else:
          return get_current_db_name()



def get_current_db_name():
    return getattr(THREAD_LOCAL, "DB", None)
© www.soinside.com 2019 - 2024. All rights reserved.