我有嵌套的序列化程序,并希望通过覆盖create方法为它创建一个实例。

时间:2018-05-07 13:13:08

标签: django-rest-framework

我的测验应用程序有两种型号,如下所示: -

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

class Quiz_Question(models.Model):
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, blank=True, default=None, null=True, related_name='questions')
    q_type = models.CharField(max_length=50)
    text = models.CharField(max_length=200)
    possible_answers = models.ManyToManyField(Answer_Options)
    selected = models.ForeignKey(Answer_Options, related_name="selected", default=None, on_delete=models.CASCADE, blank=True, null=True)
    correct = models.ForeignKey(Answer_Options, related_name="correct", default=None, on_delete=models.CASCADE, blank=True, null=True)
    order = models.IntegerField(blank=True, null=True)

现在我想为以上模型制作序列化器,如下所示: -

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

以及像这样的Quiz_Question: -

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

现在我遇到的问题是如何覆盖create()方法,以便我可以保存该问题的possible_answers并保存selected以及{{ 1}}选项correctselected选项必须是correct列表中的值。例如,如果我的possible_answers列表是[' A',' B',' C',' D'],那么possible_answers以及selected字段的值必须为correct。提前谢谢。

1 个答案:

答案 0 :(得分:0)

我已经找到了这样做的方法: -

def create(self, validated_data):
        possible_answers_data = validated_data.pop('possible_answers')
        selected_answers_data = validated_data.pop('selected')
        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']):
                    print answer.text
                    quiz_question.correct = answer                               
                quiz_question.possible_answers.add(answer)
        return quiz_question