重写的create方法不保存Django Rest Framework中的实例字段

时间:2018-05-09 11:16:48

标签: django django-rest-framework

我正在使用项目中的嵌套序列化程序。我面临一个小问题,无法猜测是什么问题。

我有两种型号: - 模型1: -

class Answer_Options(models.Model):
    text = models.CharField(max_length=200)

模型2: -

class Quiz_Question(models.Model):
    text = models.CharField(max_length=200)
    possible_answers = models.ManyToManyField(Answer_Options)
    correct = models.ForeignKey(Answer_Options, related_name="correct", default=None, on_delete=models.CASCADE, blank=True, null=True)

我为我的上述模型创建了以下序列化程序,如下所示: -

class Answer_OptionsSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Answer_Options
        fields = ('url', 'text')

对于测验问题: -

class Quiz_QuestionSerializer(serializers.HyperlinkedModelSerializer):
    possible_answers = Answer_OptionsSerializer(many=True)
    correct = Answer_OptionsSerializer()
    class Meta:
        model = Quiz_Question
        fields = ('url', 'text', 'possible_answers', 'correct')

    def create(self, validated_data):
        possible_answers_data = validated_data.pop('possible_answers')
        correct_answers_data = validated_data.pop('correct')
        quiz_question = Quiz_Question.objects.create(**validated_data)
        if possible_answers_data:
            for answer in possible_answers_data:
                answer, created  = Answer_Options.objects.get_or_create(text=answer['text'])     
                if (answer.text == correct_answers_data['text']):
                    quiz_question.correct = answer     //Not sure why this is not getting saved                          
                quiz_question.possible_answers.add(answer)
        return quiz_question

当我通过Django Rest Framework发布数据时,会调用create方法并保存可能的答案,但不知道为什么正确的答案没有为该实例保存。


我没有收到任何错误或异常。此外,我可以在Django Rest Frameworks新对象创建页面上看到正确的答案。但是,当我单击该对象的详细信息页面时,我看到正确答案的空值。
关于我做错了什么的任何线索?

我发布的示例json数据如下: -

{
    "text": "Google Headquarters are in?",
    "possible_answers": [
       {
            "text": "USA"
        },
        {
            "text": "Nort Korea"
        },
        {
            "text": "China"
        },
        {
            "text": "India"
        }
],
    "correct": {
        "text": "USA"
    }
}

1 个答案:

答案 0 :(得分:3)

您需要在更改save()值后调用correct

def create(self, validated_data):
    possible_answers_data = validated_data.pop('possible_answers')
    correct_answers_data = validated_data.pop('correct')
    quiz_question = Quiz_Question.objects.create(**validated_data)
    if possible_answers_data:
        for answer in possible_answers_data:
            answer, created  = Answer_Options.objects.get_or_create(text=answer['text'])    
            if answer.text == correct_answers_data['text']:
                quiz_question.correct = answer   
                quiz_question.save() # save changes
            quiz_question.possible_answers.add(answer)
    return quiz_question