Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST framework GET nested serializer produces an error: 'RelatedManager' object has no attribute 'datafile_set'"

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?

like image 608
Boris Burkov Avatar asked Mar 12 '23 23:03

Boris Burkov


1 Answers

You're missing a many=True argument:

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

This is required as you have a reversed FK.

like image 167
Linovia Avatar answered Apr 07 '23 15:04

Linovia