我正在尝试创建权限,以便每个用户都能够看到特定作者的文章。示例权限为Can view author1
,Can view author2
等和Can view all
。在文章类中,我尝试创建权限如下:
class Article(models.Model)
#some not important stuff
class Meta:
permissions = (
('view_%s' % Author.name, 'Can view %s' % Author.name),
('view_all', 'Can view all'),
)
这不起作用,据我所知,权限存储在数据库中,所以甚至可以通过这种方式创建权限吗?
答案 0 :(得分:0)
我认为更好的设计解决方案是:
class Author(models.Model):
...
my_allowed_viewers = models.ManyToManyField('self', related_name='views_allowed', reverse=False)
然后像
那样获得权限class IsAuthorizedReader(permissions.BasePermission):
def has_permission(self, request, view):
author_id = request.user.id
author_to_view_id = request.data.get('author_to_view_id')
if author_to_view_id is not None:
return Authors.objects.get(pk=author_to_view_id).my_allowed_viewers.filter(author_id).exists()
return False