Django Rest Create with a Writable Nested Serializer

42 views
Skip to first unread message

Ronaldo Bahia

unread,
Sep 9, 2016, 3:20:32 PM9/9/16
to Django users

Hi everyone,


I'm trying to perform a create in Django Rest Framework using a writable nested serializer.

With the code bellow I can create a ScriptQuestion but I can't add a RecordedInterview into it. Django says OrderedDict is None.

What am I doing wrong?

Thanks in advance


Thread: http://stackoverflow.com/questions/39415005/django-rest-create-with-a-writable-nested-serializer


#models.py

class ScriptQuestion(models.Model):
    interview = models.ManyToManyField(RecordedInterview)
    ...

class RecordedInterview(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    ...

The serializers

#serializers.py

class InterviewTitleSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = RecordedInterview
        fields = ('id', 'title')
        extra_kwargs = {
            'title': { 'read_only': True }
        }


class QuestionDetailSerializer(serializers.HyperlinkedModelSerializer):

    interview = InterviewTitleSerializer(many=True)

    class Meta:
        model = ScriptQuestion
        fields = ('id', 'title', 'prep_time', 'answer_time', 'interview')
        depth = 1

    def create(self, validated_data):
        interview_data = validated_data.pop('interview')
        question = ScriptQuestion.objects.create(**validated_data)
        for item in interview_data:
            item = interview_data['id']
            question.interview.add(item)
        return question

Here is my view

#views.py 

class CreateQuestion(generics.CreateAPIView):
    queryset = ScriptQuestion.objects.all()
    serializer_class = QuestionDetailSerializer

And the json

{
    "title": "Question Test Json",
    "prep_time": "1",
    "answer_time":"1",
    "interview": [
           {
                "id": "a450aeb0-8446-47b0-95bd-5accbb8b4afa"
            }
     ]
}

If I do manually, I can add the RecordedInterview into the ScriptQuestion:

#serializers.py 

def create(self, validated_data):
    interview_data = validated_data.pop('interview')
    question = ScriptQuestion.objects.create(**validated_data)
    item = 'a450aeb0-8446-47b0-95bd-5accbb8b4afa'
    question.interview.add(item)
    return question
Reply all
Reply to author
Forward
0 new messages