Django REST框架GET嵌套序列化器产生错误:' RelatedManager'对象没有属性' datafile_set'"

时间:2016-03-10 12:21:54

标签: django rest django-rest-framework

我有一个2级深度的嵌套序列化器:

class ToolSerialier(serializers.ModelSerializer):
    input = ToolInputSerializer()

    class Meta:
        model = Tool
        fields = ('docker_image', 'input')

class ToolInputSerializer(serializers.ModelSerializer):
    datafile_set = ToolInputDatafileSerializer(many=True)

    class Meta:
        model = ToolInput
        fields = ('datafile_set', )

class ToolInputDatafileSerializer(serializers.ModelSerializer):
    class Meta:
        model = ToolInputDatafile
        fields = ('name', 'file')

和各自的模型:

class Tool(models.Model):
    docker_image = models.CharField(max_length=255, null=True, blank=True)

class ToolInput(models.Model):
    tool = models.ForeignKey(Tool, related_name="input")

class ToolInputDatafile(models.Model):
        tool_input = models.ForeignKey(ToolInput, related_name="datafile_set")
        name = models.CharField(max_length=255)
        file = jsonfield.JSONField()

现在,当我向ToolSerializers列表端点发送GET请求时,收到一条错误消息:

AttributeError at /api/tool/

Got AttributeError when attempting to get a value for field `datafile_set` on serializer `ToolInputSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance. 
Original exception text was: 'RelatedManager' object has no attribute 'datafile_set'.

显然,由于某些原因,get()方法未在ToolInput的RelatedManager上调用,并且无法访问datafile_set属性。

为什么呢?我应该介绍哪些修复方法?

1 个答案:

答案 0 :(得分:5)

您错过了many=True参数:

class ToolSerialier(serializers.ModelSerializer):
    input = ToolInputSerializer(many=True)

这是必需的,因为你有一个反向的FK。