Cheng
Cheng

Reputation: 17904

Django Rest Framework how to customize ListAPIView

I have two models, Survey and Question. A Survey can contain multiple Question. I want to create a ListAPIView to return a list of Surveys with Questions associated with them. So the returned json would look like this:

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

I want to use the CursorPagination that comes with the DRF package. So here is what I have tried:

class SurveyList(ListAPIView):
    pagination_class = CursorPagination

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

Since ListAPIView's get_queryset expects a queryset to be returned. I need to manually create a JSON structure described above and put it into a queryset.

So my question is how to manually create a queryset?


Update: here is the model definition

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

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

Upvotes: 2

Views: 3267

Answers (1)

Daniil Ryzhkov
Daniil Ryzhkov

Reputation: 7596

You need to create custom serializer for your model:

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

In your view:

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

In case if you have ForeignKey to Question in your Survey model. If you don't replace question_set with name of your field.

Checkout serializers section in django rest framework documentation.

Upvotes: 3

Related Questions