Problem with many to many fieds in DRF create API

Viewed 41

when I want to save an instance of my model, many to many fields did not be saved. I tried with below codes:

models:

class Attachment(models.Model):
    test = models.TextField()


class PlanComment(models.Model):
    attachment = models.ManyToManyField('Attachment', blank=True)
    comment = models.TextField()

serializers:

class AttachmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Attachment
        fields = ['test']


class PlanCommentSerializer(serializers.ModelSerializer):
    attachment = AttachmentSerializer(many=True, read_only=True)

    class Meta:
        model = PlanComment
        fields = [
            'id',
            'attachment',
        ]

views:

class PlanCommentViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows plan comment to be viewed or edited.
    """
    queryset = PlanComment.objects.all().order_by('-id')
    serializer_class = PlanCommentSerializer

my params:

{
    "attachment": [1],
    "comment": "Test"
}
1 Answers

I changed my PlanCommentSerializer to the below code and it works fine =)

class PlanCommentSerializer(serializers.ModelSerializer):
    def __init__(self, instance=None, **kwargs):
        if instance:
            setattr(self.Meta, 'depth', 1)
        else:
            setattr(self.Meta, 'depth', 0)
        super(PlanCommentSerializer, self).__init__(instance, **kwargs)

    class Meta:
        model = PlanComment
        fields = '__all__'
        depth = 0
Related