Dynamically exclude or include a field in Django REST framework serializer

前端 未结 2 1317
滥情空心
滥情空心 2020-12-09 01:32

I have a serializer in Django REST framework defined as follows:

class QuestionSerializer(serializers.Serializer):
    id = serializers.CharField()
    quest         


        
相关标签:
2条回答
  • 2020-12-09 02:15

    Have you tried this technique

    class QuestionSerializer(serializers.Serializer):
        def __init__(self, *args, **kwargs):
            remove_fields = kwargs.pop('remove_fields', None)
            super(QuestionSerializer, self).__init__(*args, **kwargs)
    
            if remove_fields:
                # for multiple fields in a list
                for field_name in remove_fields:
                    self.fields.pop(field_name)
    
    class QuestionWithoutTopicView(generics.RetrieveAPIView):
            serializer_class = QuestionSerializer(remove_fields=['field_to_remove1' 'field_to_remove2'])
    

    If not, once try it.

    0 讨论(0)
  • 2020-12-09 02:18

    Creating a new serializer is the way to go. By conditionally removing fields in a serializer you are adding extra complexity and making you code harder to quickly diagnose. You should try to avoid mixing the responsibilities of a single class.

    Following basic object oriented design principles is the way to go.

    QuestionWithTopicView is a QuestionWithoutTopicView but with an additional field.

    class QuestionSerializer(serializers.Serializer):
            id = serializers.CharField()
            question_text = QuestionTextSerializer()
            topic = TopicSerializer()
    
    class TopicQuestionSerializer(QuestionSerializer):
           topic = TopicSerializer()
    
    0 讨论(0)
提交回复
热议问题