简体   繁体   English

如何在 Django 中检索特定模型的所有权限?

[英]How to retrieve all permissions of a specific model in django?

By default each django model has 3 permissions (add, change, delete).默认情况下,每个 django 模型都有 3 个权限(添加、更改、删​​除)。 In a model I can define my custom permission to adds more.在模型中,我可以定义我的自定义权限以添加更多。

class Company(models.Model):
    owner = models.ForeignKey(User)
    name = models.CharField(max_length=64, unique=True)
    description = models.TextField(max_length=512)
    created_on = models.DateTimeField(auto_now_add=timezone.now)

    class Meta:
        permissions = (
            ("erp_view_company", "Can see the company information"),
            ("erp_edit_company", "Can edit the company information"),
            ("erp_delete_company", "Can delete the company"),
        )

When you migrate, these permissions are automatically created at DB level.迁移时,这些权限会在数据库级别自动创建。 How can you retrieve all the permissions from a model?如何从模型中检索所有权限?

# retrieves the permissions
permissions = Permission.objects.filter(get_all_permissions_of_model_Company)
# adds permissions to group
group = Group.objects.create(name='foo', permissions=permissions)
# adds user to group
user.groups.add(group)

I would suggest you something like this:我建议你这样做:

all_permissions = Permission.objects.filter(content_type__app_label='app label', content_type__model='lower case model name')

Retrieving model's app_label :检索模型的app_label

Company._meta.app_label

Retrieving model's lower case name:检索模型的小写名称:

Company._meta.model_name

Also, you can retrieve a ContentType instance representing a model :此外,您还可以检索表示模型的ContentType实例

ContentType.objects.get_for_model(Company)

Since ContentType uses a cache, it is quite acceptable.由于ContentType使用了缓存,所以完全可以接受。 Thus, there is another way to achieve what you need:因此,还有另一种方法可以实现您的需求:

content_type = ContentType.objects.get_for_model(Company)
all_permissions = Permission.objects.filter(content_type=content_type)

you can check on codename field which will be something like: 'change_company' etc ...您可以检查codename字段,该字段类似于: 'change_company'等...

model_name = 'company'
all_perms_on_this_modal = Permission.objects.filter(codename__contains=model_name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM