DRF:将数据附加到每个响应

时间:2017-06-12 12:41:26

标签: django permissions django-rest-framework

我们正在使用Django 1.11和Django Rest Framework并尝试实现一些高级权限系统。

目前,我们有一些技术问题,其中之一是:为每个请求返回当前登录用户的链接权限(按request.user)

示例:端点http://localhost:8000/articles/1/应返回有关该文章的信息以及对用户的链接权限。 像这样:

{'title': 'Article Title', 'pages': 50, 'permissions': ['can_read_article', 'can_update_article'] ...}

应在Django Admin>内部管理这些权限。用户&小组系统。

非常感谢,任何帮助都将不胜感激

1 个答案:

答案 0 :(得分:0)

You can try to achieve this by using Serializer Method Field to grab that information:

class ArticleSerializer(serializers.ModelSerializer):
    permissions = serializers.SerializerMethodField()

    def get_permissions(self, obj):
        user = self.context['request'].user

        # compute permissions
        #permissions = user.get_all_permissions() # if you are using Django's permissions, see note below
        permissions = get_perms(user, obj) # if you are using django-guardian

        return permissions

Note that if you are using Django's permissions from django.contrib.auth which has no object level permissions, I do not thing your approach is the optimal one: Instead of returning all the permissions on each request, it would be more efficient to grab all user's permissions by a separate call and store that somewhere in your frontend to use it later. On the other hand, if you are using object level permissions, like with django-guardian then this approach seems suitable.