django - 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
解决方案
正如我们在源代码 [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()
推荐阅读
- maven - 在 pom.xml 中用于 maven 配置我无法理解 $
- apache-kafka - 如何更新 Kafka/Kafka 流中的数据?
- python - 如何在 python 中解码 \xe2\x80\xa6?
- ssis - 使用来自一个数据流任务的目标平面文件作为另一个数据流任务的源
- tensorflow - 如何保存具有常量的自定义层的 keras 模型?
- javascript - 允许从 url 读取 Angular 中的特殊字符
- scapy - 警告:发送 ipv6 数据包时未找到到达目的地的 Mac 地址
- javascript - Rails 6:通过 Webpacker 包含 3rd Party Yarn 库
- c++ - 具有模板模板参数的类的专业化在clang中但在gcc中不起作用
- python - 在 python 中以 w+b 模式解压