[Django]-How to filter Foreign Key relations on Django serializers?

3๐Ÿ‘

โœ…

I think youโ€™ll get desired output if you slightly change the get_quesyset() method.

class QuestionList(generics.ListAPIView):
    def get_queryset(self):
        return Question.objects.all()

    serializer_class = QuestionSerializer

When you access the QuestionList list api you will get the output as follows

[
    {
        "id": 4,
        "question_name": "qus-1",
        "answer_questions": [
            {
                "id": 5,
                "score": 50,
                "question_id": 4,
                "paper_id": 4
            },
            {
                "id": 6,
                "score": 10,
                "question_id": 4,
                "paper_id": 5
            }
        ]
    },
    {
        "id": 5,
        "question_name": "qus-2",
        "answer_questions": []
    },
    {
        "id": 6,
        "question_name": "que-3",
        "answer_questions": [
            {
                "id": 7,
                "score": 342,
                "question_id": 6,
                "paper_id": 4
            }
        ]
    }
]

Update-1

Change your serializer as below

class QuestionSerializer(serializers.ModelSerializer):
    answer_questions = serializers.SerializerMethodField()

    def get_answer_questions(self, question):
        paper_id = self.context['view'].kwargs.get('paper_id')
        return AnswerSerializer(question.answer_questions.filter(paper_id=paper_id), many=True).data

    class Meta:
        fields = ('id', 'question_name', 'answer_questions')
        model = Question
๐Ÿ‘คJPG

Leave a comment