使用Rest Framework从模型序列化嵌套对象时出现序列化器错误

时间:2019-05-06 06:24:05

标签: django django-models django-rest-framework django-serializer

我看过一些相关的帖子,但是我不确定该怎么做。

我已经建立了一个视图来序列化具有嵌套模型的测试模型。我已经设置了序列化程序,但收到错误消息“尝试获取序列化程序Question上字段TestSerializer的值时出现AttributeError。\ n序列化程序字段的名称可能不正确”。

我的序列化器:

class AnswerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Answer
        fields = ('id', 'number', 'text', 'iscorrect')

class QuestionSerializer(serializers.ModelSerializer):
    answer = AnswerSerializer()

    class Meta:
        model = Question
        fields = ('id', 'number', 'text', 'answer')
        related_object = 'answer'

class TestSerializer(serializers.ModelSerializer):
    question = QuestionSerializer()

    class Meta:
        model = Test
        fields = ('id', 'name', 'question')
        related_object = 'question'

我的模特:

class Test(models.Model):
    user = models.ForeignKey(User, on_delete=models.PROTECT)
    name = models.CharField(max_length=255,default='',blank=False)
    datecreated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

class Question(models.Model):
    test = models.ForeignKey(Test, on_delete=models.CASCADE)
    text = models.CharField(max_length=255,default='',blank=False)
    number = models.IntegerField()

    def __str__(self):
        return self.text

class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    text = models.CharField(max_length=255,default='',blank=False)
    number = models.IntegerField()
    iscorrect = models.BooleanField(default=False)

    def __str__(self):
        return self.text

视图调用:

serializer = TestSerializer(test, many=True)

1 个答案:

答案 0 :(得分:0)

您已经在外键中设置了related_name,否则默认的相关名称是{model_name} _set。

class Question(models.Model):
  test = models.ForeignKey(Test, on_delete=models.CASCADE, related_name='questions')
  text = models.CharField(max_length=255,default='',blank=False)
  number = models.IntegerField()

  def __str__(self):
     return self.text

在序列化程序中,您可以访问该字段

class TestSerializer(serializers.ModelSerializer):
  questions = QuestionSerializer(many=True)

  class Meta:
    model = Test
    fields = ('id', 'name', 'question')
    related_object = 'question'