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

时间:2016-07-15 08:45:25

标签: python django django-models permissions

默认情况下,每个django模型都有3个权限(添加,更改,删除)。在模型中,我可以定义我的自定义权限以添加更多。

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"),
        )

迁移时,会在数据库级别自动创建这些权限。如何从模型中检索所有权限?

# 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)

2 个答案:

答案 0 :(得分:11)

我建议你这样:

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

检索模型' app_label

Company._meta.app_label

检索模型的小写名称:

Company._meta.model_name

另外,您可以retrieve a ContentType instance representing a model

ContentType.objects.get_for_model(Company)

由于ContentType使用缓存,因此完全可以接受。因此,还有另一种方法可以实现您的需求:

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

答案 1 :(得分:1)

您可以查看codename字段,例如:'change_company'等...

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