【发布时间】:2015-03-12 04:49:14
【问题描述】:
我在 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
一种解决方案是编写两个不同的序列化程序。但是必须有一个更简单的解决方案来有条件地从给定的序列化程序中排除一个字段。
【问题讨论】:
标签: python django serialization django-rest-framework django-serializer