首页 > 解决方案 > Django:如何为权限创建 ContentType 对象?

问题描述

我正在尝试在后端组和权限中创建。

现在我试图了解什么是content_type参数以及在创建权限时如何使用它。

权限模型的文档说

内容类型¶

必需的。对 django_content_type 数据库表的引用,其中包含每个已安装模型的记录。

我怎样才能得到这个 content_type?我应该在哪里寻找它?

我使用 PosgresSQL 作为数据库。

根据this other question,可以这样做:

from django.contrib.auth.models import User, Group, Permission
from django.contrib.contenttypes.models import ContentType

content_type = ContentType.objects.get(app_label='app_name', model='model_name')
permission = Permission.objects.create(codename='can_create_hr',
                                       name='Can create HR',
                                       content_type=content_type) # creating permissions
group = Group.objects.get(name='HR')
group.permissions.add(permission)

但同样,app_label='app_name', model='model_name'里面是什么:
content_type = ContentType.objects.get(app_label='app_name', model='model_name')

我的项目结构:

stickers-gallito-app
    |_cart
    |_shop

标签: django

解决方案


正如我们在源代码 [GitHub]中看到的,它指的是ContentType模型 [Django-doc]

class Permission(models.Model):

    #  ...

    name = models.CharField(_('name'), max_length=255)
    content_type = models.ForeignKey(
        ContentType,
        models.CASCADE,
        verbose_name=_('content type'),
    )
    codename = models.CharField(_('codename'), max_length=100)

AContentType是一个模型来引用模型类。如果你安装了contentype应用程序,那么 Django 将维护这样的表并“维护”它:这意味着如果你添加一个额外的模型,Django 会自动为ContentType模型添加一个条目。您可以在数据库中看到这些值(通常在django_content_type表格下方)。

模型类在 中定义app,并且该应用程序具有标签。此外,模型本身也有名称。例如对于User模型,我们看到:

>>> from django.contrib.auth.models import User
>>> User._meta.app_label
'auth'
>>> User._meta.model_name
'user'

因此可以通过app_label和指定模型model_name

model_class例如,您可以通过以下方法获取对该内容类型的类的引用:

mypermission.content_type.model_class()

推荐阅读