如何自动将CRUD权限添加到Meta类中的django模型?

时间:2018-03-20 20:38:48

标签: django django-models permissions authorization django-guardian

想象一下,我有以下模型

NSCalendar* _cal = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
[_cal setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents* resultComponents = [_cal components:NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitMonth fromDate:result]; 
//result is 2018-03-18 05:48:36 +0000

//resultComponents 
//<NSDateComponents: 0x60400014f0a0>
//Month: 3
//Leap month: no
//Day: 18
//Hour: 0
//Minute: 48

我想要的是生成元组的class Post(models.Model): name = models.CharField(max_length=20) body = models.TextField() class Meta: permissions = permission_generator()

permission_generator()

我可以在所有模型中重复使用,而不必在每次定义新模型时重复自己。

如何实现这样的事情?

2 个答案:

答案 0 :(得分:0)

我发现django默认添加了

  • add_modelname
  • change_modelname
  • delete_modelname

https://docs.djangoproject.com/en/dev/topics/auth/default/#default-permissions

答案 1 :(得分:0)

您可以创建抽象模型并继承它。例如:

class BaseModel(models.Model):
    class Meta:
        abstract=True
        permissions = (
            ('create', 'Create'),
            ('read', 'Read'),
            ('update', 'Update'),
            ('delete', 'Delete')
        )

class Cat(BaseModel):
    name = models.CharField()

当您继承该模型并进行数据迁移时,这些权限将添加到django_permissions表中,如下所示:

app | cat | Permission name