【问题标题】:Django: how to create a ContentType Object for a Permission?Django:如何为权限创建 ContentType 对象?
【发布时间】:2019-05-05 19:29:37
【问题描述】:

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

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

Documentation for Permission model says:

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


    【解决方案1】:

    正如我们在source code [GitHub] 中看到的,它指的是ContentType model [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)

    ContentType 是引用模型类的模型。如果你安装了 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_labelmodel_name 指定模型。

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

    mypermission.content_type.<b>model_class()</b>

    【讨论】:

    • 请在此处查看我与此问题相关的更新:stackoverflow.com/questions/55989579/…
    • 创建权限时使用django_content_type表中的哪条记录的逻辑是什么?
    • @OmarGonzales:在引用的问题中,您的Permissions 很可能已经存在。您可以通过 name 属性搜索这些。例如Can add user 已经存在,并链接到User 模型,但这无关紧要。
    猜你喜欢
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2013-08-30
    • 2013-09-18
    • 1970-01-01
    相关资源
    最近更新 更多