2016-07-15 106 views
2

默认情况下,每个django模型有3个权限(添加,更改,删除)。在模型中,我可以定义自定义权限以添加更多内容。如何在django中检索特定模型的所有权限?

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) 

回答

5

我建议你这样的事情:

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) 
+0

好的,谢谢你的支持! – realnot

1

您可以检查codename场,这将是这样的:'change_company'等...

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

我刚才看到,该表的权限有contentt_ype_id是中值的表django_content_type外键。而不是使用代号,使用模型不是更好吗? – realnot

+1

@realnot我不会使用contenttype,codename没有连接,所以它更便宜 – doniyor

+0

好的,谢谢你的支持! – realnot

相关问题