相关疑难解决方法(0)

在Django REST框架序列化程序中动态排除或包含字段

我在Django REST框架中有一个序列化程序,定义如下:

class QuestionSerializer(serializers.Serializer):
    id = serializers.CharField()
    question_text = QuestionTextSerializer()
    topic = TopicSerializer()
Run Code Online (Sandbox Code Playgroud)

现在我有两个使用上述序列化程序的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
Run Code Online (Sandbox Code Playgroud)

一种解决方案是编写两个不同的序列化器.但必须有一个更容易的解决方案来有条件地从给定的序列化器中排除一个字段.

python django serialization django-serializer django-rest-framework

31
推荐指数
2
解决办法
1万
查看次数