How to dynamically remove fields from serializer output

前端 未结 3 1012
别那么骄傲
别那么骄傲 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条回答
  • 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 
    
    0 讨论(0)
  • 2021-01-01 11:43

    My problem was somewhat similar to yours and I solved it with inheritance.

    class StaticSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = StaticModel
            fields = (
                'first_name', 'last_name', 'password', 'username',
                'email'
            )
    
    
    class DynamicSerializer(StaticSerializer):
    
        class Meta:
            model = StaticModel
            fields = (
                'first_name',
            )
    
    0 讨论(0)
  • 2021-01-01 11:49

    You can create multiple serializers and choose the proper one in view

    class IndexView(APIView):
        def get_serializer(self):
            if self.request.GET['flag']:
                return SerializerA
            return SerializerB
    

    use inheritance to make serializers DRY.

    0 讨论(0)
提交回复
热议问题