python - Django Rest Framework-可写嵌套序列化器错误

标签 python django

我正在尝试创建一个测验应用程序,我是 dajango 和 rest 的初学者,我正在尝试创建一个序列化程序来创建带有选择的新问题,我也不太了解可写嵌套序列化程序的工作原理,如果有人能给出一个工作示例

模型.py:

class Question(models.Model):
    quiz = models.ForeignKey(Quiz, related_name="question")
    question = models.CharField(max_length=200)

    def __unicode__(self):
        return self.question 

class Choice(models.Model):
    question = models.ForeignKey(Question, related_name="choice")
    choice = models.CharField(max_length=200)
    correct_answer = models.BooleanField(default=False)

    def __unicode__(self):
        return self.choice

序列化程序.py:

class createChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Choice
        fields = ('choice','correct_answer',)

class createQuestionSerializer(serializers.ModelSerializer):
    choices = createChoiceSerializer()
    class Meta:
        model = Question

    def create(self, validated_data):
        choices_data = validated_data.pop('choices')
        question = Choice.objects.create(**validated_data)
        for choice in choices_data:
            try:
                choice = Choice.objects.get(name=choice["name"])
            except Choice.DoesNotExist:
                choice = Choice.objects.create(**choice)
            question.choices.add(choice)
        return question

当我写问题和选择时出现错误: /questions/create 处的 ValueError

无法分配“u”你叫什么名字“”:“Choice.question”必须是一个“问题”实例。

最佳答案

question = Choice.objects.create(**validated_data)

question 是一个 Choice 实例,question.choices.add(choice) 基本上将 Choice 添加到 Choice 实例。

您可以尝试 Question.objects.create(**validated_data)。我不确定这是否有效,但至少解决了您现在遇到的错误。

关于python - Django Rest Framework-可写嵌套序列化器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28504048/

相关文章:

python - 创建列表字典的速记?

Django 装置。加载初始数据进程被终止

python - 在 Django 中自动生成自定义迁移

database - 如何转储 django-cms 相关内容以便与正在运行的实例一起迁移?

python - 带有 seaborn 的 Jointplot 多索引列

python - 将背景颜色扩展到连接的组件(洪水填充) - 图像处理

python 将 "\n"转义字符与 "\\n"进行比较

python - 从 Pandas DataFrame 计算 IDF

python - makemigrations reponses 指定 app_label 时未检测到任何更改

python - 如何在 Django 中对搜索结果进行分页?