Per Field Permission in Django REST Framework

前端 未结 7 2289
既然无缘
既然无缘 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:09

    For a solution that allows both reading and writing, do this:

    class PrivateField(serializers.Field):
        def get_attribute(self, obj):
            # We pass the object instance onto `to_representation`,
            # not just the field attribute.
            return obj
    
        def to_representation(self, obj):
            # for read functionality
            if obj.created_by != self.context['request'].user:
                return ""
            else:
                return obj.private_field1
    
        def to_internal_value(self, data):
            # for write functionality
            # check if data is valid and if not raise ValidationError
    
    
    class UserInfoSerializer(serializers.HyperlinkedModelSerializer):
        private_field1 = PrivateField()
        ...
    

    See the docs for an example.

提交回复
热议问题