Per Field Permission in Django REST Framework

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

    In case you are performing only READ operations, you can just pop the fields in to_representation method of the serializer.

    def to_representation(self,instance):
        ret = super(YourSerializer,self).to_representation(instance)
        fields_to_pop = ['field1','field2','field3']
        if instance.created_by != self.context['request'].user.id:
            [ret.pop(field,'') for field in fields_to_pop]
        return ret
    

    This should be enough to hide sensitive fields.

提交回复
热议问题