首页 > 解决方案 > 覆盖的创建方法未在 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 new object created page 上看到正确答案。但是,当我单击该对象的详细信息页面时,我会看到正确答案的空值。
任何线索我做错了什么?

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

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

标签: djangodjango-rest-framework

解决方案


您需要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

推荐阅读