Search code examples
pythondjangoserializationdjango-rest-frameworkdjango-serializer

Dynamically exclude or include a field in Django REST framework serializer


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

class QuestionSerializer(serializers.Serializer):
    id = serializers.CharField()
    question_text = QuestionTextSerializer()
    topic = TopicSerializer()

Now I have two API views that use the above serializer:

class QuestionWithTopicView(generics.RetrieveAPIView):
    # I wish to include all three fields - id, question_text
    # and topic in this API.
    serializer_class = QuestionSerializer

class QuestionWithoutTopicView(generics.RetrieveAPIView):
    # I want to exclude topic in this API.
    serializer_class = ExamHistorySerializer

One solution is to write two different serializers. But there must be a easier solution to conditionally exclude a field from a given serializer.


Solution

  • 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.