现在我有这样的models.py
class FileCategory(models.Model):
file_type = models.CharField(_('type'), max_length=128)
def __unicode__(self):
return self.file_type
class Doc(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
file_category = models.ForeignKey('FileCategory', null=True)
file = models.FileField(upload_to='documents/',
null=True, blank=True)
class Meta:
permissions = (("upload_file", "upload file"),
("delete_file", "delete file"),
("download_file", "download file"),
("access_file", "access file"),
)
现在我想为每个FileCategory
表添加权限
例如,如果我有filecategory numm,dumm和summ
我想自动拥有权限("access_file_numm","access_file_summ","access_file_dumm", )
我试图制作这样的解决方案:
permissions = (bla,bla,bla,
)+\
("access_file_%s" (type.__str__() for type in FileCategory.objects.all()),
"access %s"(type.__str__() for type in FileCategory.objects.all()))
确定我想将它们迁移到数据库
当Moemn用编辑回答:
def save(self, *args, **kwargs):
super(FileCategory, self).save(*args, **kwargs)
Permission.objects.get_or_create(content_type=ContentType.objects.get_for_model(Doc),
codename="access_type_%s" % self.file_type,
name="access type %s" % self.file_type)
答案 0 :(得分:1)
您可以在每次Permission
创建后动态创建FileCategory
来执行此操作。
e.g。
def save(self, *args, **kwargs):
super(FileCategory, self).save(*args, **kwargs)
Permission.objects.create(content_type=ContentType.get_for_model(Doc), name="access_file_%s" % self.file_type)
Permission.objects.create(content_type=ContentType.get_for_model(Doc), name="access_%s" % self.file_type)
或者你可以使用信号,同样的想法。