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 new object created page 上看到正确答案。但是,当我单击该对象的详细信息页面时,我会看到正确答案的空值。
任何线索我做错了什么?
我发布的示例 json 数据如下:-
{
"text": "Google Headquarters are in?",
"possible_answers": [
{
"text": "USA"
},
{
"text": "Nort Korea"
},
{
"text": "China"
},
{
"text": "India"
}
],
"correct": {
"text": "USA"
}
}
解决方案
您需要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
推荐阅读
- php - PHP Imagick PDF 到 JPEG 字符间距问题
- arduino - 具有 LED 的手动和自动功能
- r - 如何将 + geom_line() 与分类 x 变量和定量 y 变量一起使用
- css - 添加媒体查询后,CSS 将无法按预期工作
- node.js - AWS S3 - 图像无法显示,因为它包含错误
- haskell - 如何从 Haskell 中的不同类型级别强制类型?
- php - 如何在双引号字符串中使用类常量?
- javascript - Adding var's together
- php - 如何使用php和mysql删除数据
- javascript - C# 中的 Forge.min.js RSA 加密