Django Rest使用可写的嵌套Serializer创建

时间:2016-09-09 15:26:27

标签: python django nested django-rest-framework

我尝试使用可写嵌套序列化程序在Django Rest Framework中执行创建。

使用下面的代码我可以创建一个ScriptQuestion但我无法在其中添加RecordedInterview。 Django说OrderedDict是None。

我做错了什么?

提前致谢

#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)
    ...

序列化程序

#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

这是我的观点

#views.py 

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

和json

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

如果我手动操作,我可以将RecordedInterview添加到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

2 个答案:

答案 0 :(得分:0)

由于声誉低,我无法添加评论。添加作为答案。我认为你应该使用' serializers.ModelSerializer'而不是' serializers.HyperLinkedModelSerializer'

答案 1 :(得分:0)

哦,我能成功。

对于将来的某个人,只需添加" id = serializers.CharField()"在串行器中

class InterviewTitleSerializer(serializers.ModelSerializer):
    id = serializers.CharField()

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