【问题标题】:Problem with many to many fieds in DRF create APIDRF创建API中多对多字段的问题
【发布时间】:2020-03-11 10:24:22
【问题描述】:

当我想保存我的模型的一个实例时,多对多的字段没有被保存。 我尝试了以下代码:

型号:

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


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

序列化器:

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',
        ]

观看次数:

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

我的参数:

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

【问题讨论】:

  • 删除read_only=True
  • @ArakkalAbu 未设置 read_only 时,附件不能是 params 中的 PK 列表。

标签: python django python-3.x django-rest-framework


【解决方案1】:

我将我的 PlanCommentSerializer 更改为以下代码,它工作正常 =)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 2022-08-10
    • 2016-06-27
    相关资源
    最近更新 更多