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

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

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

我知道如何读取/创建特定数据库的记录,但不太确定如何创建特定数据库的相关表记录。而且 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') 

# Need to run below to specific database 'db' instead of default
user.groups.add(admin_group)
sql django database model
1个回答
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”),以确保在目标数据库上执行数据操作。

© www.soinside.com 2019 - 2024. All rights reserved.