How to filter queryset for serializing a nested serializer using instance in django rest framework?

1,984 views
Skip to first unread message

Rahul Sarma

unread,
May 29, 2019, 11:28:32 AM5/29/19
to Django REST framework
My serializers.py file:

from rest_framework import serializers

   
from diagnosisApp.models import Question, Option


   
class OptionSerializer(serializers.ModelSerializer):

       
class Meta:
            model
= Option
            fields
= ('id', 'content')


   
class QuestionSerializer(serializers.Serializer):
        content
= serializers.CharField()
        options
= OptionSerializer(
           
Option.objects.filter(optiongroup__question=**insert instance value here**).distinct(),
            many
=True
           
)

I'm trying to create a nested OptionSerializer inside QuestionSerializer but I need to filter the queryset based on the question instance which will be passed during initialization in this section: `optiongroup__question=**insert instance value here**`. How do I do this?

P.S: Please don't tell me to use ModelSerializer or SerializerMethodField because options is not directly related to Question and the options field needs to be writable.
Reply all
Reply to author
Forward
0 new messages