Per Field Permission in Django REST Framework

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

    I had a similar problem the other day. Here is my approach:

    This is a DRF 2.4 solution.

    class PrivateField(serializers.Field):
        def field_to_native(self, obj, field_name):
            """
            Return null value if request has no access to that field
            """
            if obj.created_by == self.context.get('request').user:
                return super(PrivateField, self).field_to_native(obj, field_name)
            return None
    
    #Usage
    class UserInfoSerializer(serializers.ModelSerializer):
        private_field1 = PrivateField()
        private_field2 = PrivateField()
    
        class Meta:
            model = UserInfo
    

    And a DRF 3.x solution:

    class PrivateField(serializers.ReadOnlyField):
    
        def get_attribute(self, instance):
            """
            Given the *outgoing* object instance, return the primitive value
            that should be used for this field.
            """
            if instance.created_by == self.context['request'].user:
                return super(PrivateField, self).get_attribute(instance)
            return None
    

    This time we extend ReadOnlyField only because to_representation is not implemented in the serializers.Field class.

提交回复
热议问题