Django Rest Framework如何自定义ListAPIView

时间:2015-12-07 13:34:51

标签: python django rest django-rest-framework

我有两个模型,SurveyQuestionSurvey可以包含多个Question。我想创建一个ListAPIView来返回与Surveys相关联的Questions列表。所以返回的json看起来像这样:

[{
     'name': 'Survey 1',
     'questions':[{'question': 'q1'}, {'question': 'q2'}]
 },
 {
     'name': 'Survey 2',
     'questions':[{'question': 'q3'}, {'question': 'q4'}]
 },
 ...
]

我想使用DRF包附带的CursorPagination。所以这就是我的尝试:

class SurveyList(ListAPIView):
    pagination_class = CursorPagination

    def get_queryset(self):
        # How can I construct a queryset that matches the JSON structure above?

由于ListAPIView的get_queryset需要返回一个查询集。我需要手动创建上面描述的JSON结构并将其放入查询集中。

所以我的问题是如何手动创建查询集?

更新:这是模型定义

class Survey(models.Model):
    name = models.TextField()

class Question(models.Model):
    question = models.TextField()
    survey = models.ForeignKey(Survey)

1 个答案:

答案 0 :(得分:3)

您需要为您的模型创建自定义序列化程序:

class QuestionSerializer(serializers.ModelSerializer):

    class Meta:
        model = Question
        fields = ('question',)

class SurveySerializer(serializers.ModelSerializer):
    questions = QuestionSerializer(source="question_set", many=True)

    class Meta:
        model = Survey
        fields = ('name', 'questions')
        depth = 1

在您看来:

class SurveyList(ListAPIView):
     queryset = Survey.objects.all()
     serializer_class = SurveySerializer

如果您的ForeignKey模型中有QuestionSurvey。如果您不将question_set替换为您的字段名称。

在django rest框架文档中签出serializers section