如何使用外键创建对象

时间:2017-07-12 02:37:58

标签: json django rest foreign-key-relationship serializer

Fisrt,这是我的模特:

class Question(models.Model):
    description = models.CharField(max_length=200)
    analysis = models.CharField(max_length=50)

    def __str__(self):
        return self.description


class QuestionOption(models.Model):
    question = models.ForeignKey(Question,related_name='options')
    content = models.CharField(max_length=100)
    isAnswer = models.BooleanField()

    def __str__(self):
        return self.question.description + " " + self.content

我的序列化器:

class QuestionSerializer(ModelSerializer):
    class Meta:
        model = Question
        fields = '__all__'

Serializer的{​​{1}}同样

我的ViewSet:

QuestionOption

我想发布一个Json数据,如下所示:

class QuestionViewSet(ModelViewSet):
    queryset = Question.objects.all()
    serializer_class = QuestionRetriveSerilzer

我希望我的{ "options": [ { "content": "This is the first option", "isAnswer": false }, { "content": "This is the second option", "isAnswer": true } ], "description": "which one is true?", "analysis": "It's esay" } 可以自动为我创建QuestionViewSet和两个Question,当我发布Json数据时,QuestionOption是空列表,所以我覆盖options的{​​{1}}方法,如下所示:

create

这种方法可行,但我想找到一种更简单的方法,因为我必须覆盖QuestionViewSet和其他方法,这不是一件容易的事......

那么如何设计 def create(self, request, *args, **kwargs): serializer = QuestionSerializer(data=request.data) question = serializer.save() for data in request.data['options']: data['question'] = question.id optionSeializer = OptionSerializer(data=data) print optionSeializer.is_valid() optionSeializer.save() return Response(serializer.data,status=status.HTTP_200_OK) update以便自动创建对象并使用外键更新对象?

1 个答案:

答案 0 :(得分:0)

drf-writable-nested可能会有所帮助。