我有一个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
属性。
为什么呢?我应该介绍哪些修复方法?
答案 0 :(得分:5)
您错过了many=True
参数:
class ToolSerialier(serializers.ModelSerializer):
input = ToolInputSerializer(many=True)
这是必需的,因为你有一个反向的FK。