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

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/01dd7e85-2281-4fe4-99b9-30a6669b6862%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to