[英]How to retrieve all permissions of a specific model in django?
默認情況下,每個 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)
我建議你這樣做:
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
此外,您還可以檢索表示模型的ContentType
實例:
ContentType.objects.get_for_model(Company)
由於ContentType
使用了緩存,所以完全可以接受。 因此,還有另一種方法可以實現您的需求:
content_type = ContentType.objects.get_for_model(Company)
all_permissions = Permission.objects.filter(content_type=content_type)
您可以檢查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.