Django:如何通过命令创建组? [英] Django: How to create a Group through a command?

查看:63
本文介绍了Django:如何通过命令创建组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想自动化数据库中所有的数据创建,为此我使用了不同的命令.

I want to automate all the data creation on my data base, for this I'm using different commands.

我知道如何为我的模型执行此操作,因为我知道其领域.

I know how to do this for my models, because I know its fields.

但是对于组模型如何做到这一点?

from django.contrib.auth.models import Group

查询其字段时,我得到:用户","id",名称",权限"

When I query its fields I get: 'user', 'id', 'name', 'permissions'

[f.name for f in Group._meta.get_fields()]

但是在管理面板中,我仅看到要创建一个组,需要 name permission 字段:

But in Admin Panel I only See that in order to create a Group the name and the permission fields are required:

命令:

import pandas as pd
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand



tmp_data_groups=pd.read_csv('static/data/groups.csv',sep=',', encoding='iso-8859-1').fillna(" ")



class Command(BaseCommand):
    def handle(self, **options):
        groups = [
            Group(
                name=row['name'],
                permissions=row['permissions']
        )
            for _, row in tmp_data_groups.iterrows()
        ]

        Group.objects.bulk_create(groups)

我收到此错误(通过命令或在shell中):

I get this error (with the command or in shell):

TypeError:直接分配给多对多集的正向被禁止.改用Permissions.set().

TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use permissions.set() instead.

使用外壳的示例:

我有一个名为客户"的小组,它已经分配了所有权限.

I've a Group named "Clientes" and it has assigned all the permisions.

Group.objects.all()[0].permissions.all() #Clientes is the only group created

我想创建一个名为"NuevosClientes"(英文为NewClients)的新组.

I wan to create a new group called "NuevosClientes" (NewClients in english).

Group.objects.create(name='NuevosClientes', permissions='Can view user')

对此进行了尝试,但得到了:

Tried this but got:

TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use permissions.set() instead.

我应该如何准备读取CSV字段并使用命令生成所需的新组?

| name           | permissions        |   |   |   |
|----------------|--------------------|---|---|---|
| NuevosClientes | Can view user      |   |   |   |
| NuevosClientes | Can add permission |   |   |   |
| NuevosClientes | Can delete user    |   |   |   |
| NuevosClientes | Can delete cart    |   |   |   |

更新1 :

我已经创建了组,但是现在我需要创建要添加到这些组的权限.

I've created my groups, but now I need to create the Permissions to be added to these groups.

但是为了创建权限,我还需要创建ContentType对象.

But in order to create the Permissions I also need to create the ContentType objects.

但是,ContentType对象具有这些参数.

How ever, the ContentType object has these arguments.

content_type = ContentType.objects.get(app_label='app_name', model='model_name')

根据在另一篇文章中的提问,每次我们在 django_content_type 表中创建模型条目时,都会在该表中为该模型添加新记录.

According to this asnwer in another post, everytime we create model an entry in the django_content_type table a new record is added in this table for said model.

我应该使用什么条目来创建ContentType对象?app_label ='app_name'和model ='model_name'的值应该是什么?

What entry should I use to create the ContentType object? What should be the values for app_label='app_name' and model='model_name'?

django_content_type 表中有很多条目:

`logentry`, `permission`, `group`, `user`, `contenttype`, `session`, and also for my own models. 

推荐答案

如果与该关系相关的对象已经保存,则只能将项目添加到多对多关系中.

You can only add items to a many-to-many relation, if the objects that are related to that relation are already saved.

因此,您可能首先要保存已构建的 Group ,然后添加权限.请注意, <代码> Permission [Django-doc] 也是一个模型,因此您不能仅在此处使用字符串.

So you probably first want to save the Group you have constructed, and then add the permission. Note that Permission [Django-doc] is a model as well, so you can not just use a string here.

您的命令将因此如下所示:

Your command will thus look like:

from django.contrib.auth.models import Group, Permission

# ...

g1 = Group.objects.create(name=row['name'])
p1, __ = Permission.objects.get_or_create(name=row['permissions'])
g1.permissions.add(p1)

因此,我们首先构造一个具有给定名称的 Group 对象,然后检索相关的 Permission 对象,然后添加该权限 p1 转到给定组的权限.如果可以有多个权限,则需要使其更加复杂.

We thus first construct a Group object with a given name, then we retrieve the related Permission object, and then we add that permission p1 to the permissions of the given group. If there can be multiple permissions, you will need to make it a bit more sophisticated.

您仍然可以通过执行两遍操作来使用 bulk_create :首先,使用给定名称构造所有组,然后在第二遍中,检索所有相关权限并正确设置这些权限.

You can still use bulk_create by performing two passes: first you construct all the groups with the given names, and then in a second pass you retrieve all the related permissions and set these correctly.

这篇关于Django:如何通过命令创建组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆