Per Field Permission in Django REST Framework

前端 未结 7 2311
既然无缘
既然无缘 2020-12-24 01:25

I am using Django REST Framework to serialize a Django model. I have a ListCreateAPIView view to list the objects and a RetrieveUpdateDestroyAPIView view to retrieve/update

7条回答
  •  清歌不尽
    2020-12-24 02:18

    I figured out a way to do it. In the serializer, I have access to both the object and the user making the API request. I can therefore check if the requestor is the owner of the object and return the private information. If they are not, the serializer will return an empty string.

    class UserInfoSerializer(serializers.HyperlinkedModelSerializer):
        private_field1 = serializers.SerializerMethodField('get_private_field1')
    
        class Meta:
            model = UserInfo
            fields = (
                'id',
                'public_field1',
                'public_field2',
                'private_field1',
            )
            read_only_fields = ('id')
    
        def get_private_field1(self, obj):
            # obj.created_by is the foreign key to the user model
            if obj.created_by != self.context['request'].user:
                return ""
            else:
                return obj.private_field1
    

提交回复
热议问题