I've got a 2-level-deep stack of nested serializers:
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')
and respective models:
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()
Now, when I send a GET request to ToolSerializers list endpoint, I get an error message:
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'.
Clearly, for some reason, get()
method was not called on RelatedManager
of ToolInput and it fails to access datafile_set
attribute.
Why? What fixes should I introduce?
You're missing a many=True
argument:
class ToolSerialier(serializers.ModelSerializer):
input = ToolInputSerializer(many=True)
This is required as you have a reversed FK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With