我在Django REST框架中有一个序列化程序,定义如下:
class QuestionSerializer(serializers.Serializer):
id = serializers.CharField()
question_text = QuestionTextSerializer()
topic = TopicSerializer()
现在我有两个使用上述序列化程序的API视图:
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
一个解决方案是写两个不同的串行器。但是,必须有一个更简单的解决方案来有条件地从给定的序列化程序中排除字段。