How to dynamically remove fields from serializer output

前端 未结 3 1024
别那么骄傲
别那么骄傲 2021-01-01 11:08

I\'m developing an API with Django Rest framework, and I would like to dynamically remove the fields from a serializer. The problem is that I need to remove them depending o

3条回答
  •  梦毁少年i
    2021-01-01 11:41

    You can customize the serialization behavior by overriding the to_representation() method in your serializer.

    class DynamicSerliazer(serializers.ModelSerializer):
    
        def to_representation(self, obj):
            # get the original representation
            ret = super(DynamicSerializer, self).to_representation(obj)
    
            # remove 'url' field if mobile request
            if is_mobile_platform(self.context.get('request', None)):
                ret.pop('url')
    
            # here write the logic to check whether `elements` field is to be removed 
            # pop 'elements' from 'ret' if condition is True
    
            # return the modified representation
            return ret 
    

提交回复
热议问题