【发布时间】: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