我有以下Django模型:
class Task(models.Model):
'''Task needed to complete a goal'''
title = models.CharField(max_length=200)
class Issue(models.Model):
'''Issue from different forges'''
title = models.CharField(max_length=200, blank=True)
tasks = models.ManyToManyField(Task)
我有以下序列化程序:
class TaskSerializer(serializers.ModelSerializer):
'''Serializer to represent the Task model'''
class Meta:
model = Task
fields = ("id", "title")
class IssueSerializer(serializers.ModelSerializer):
'''Serializer to represent the issue model'''
tasks = TaskSerializer(read_only=True, many=True)
class Meta:
model = Issue
fields = ("title", "tasks")
现在我的POST请求如下:
{
"id": null,
"title": "",
"tasks": [14]
}
该问题的空标题,因为我将提供这一个服务器端所以我需要重新定义IssueViewSet的create(),如下所示:
class IssueViewSet(viewsets.ModelViewSet):
'''ViewSet for viewing and editing Issue objects'''
queryset = Issue.objects.all().order_by('id')
serializer_class = IssueSerializer
def create(self, request):
serializer = IssueSerializer(data=request.data)
if serializer.is_valid():
issue = Issue(title='test', tasks=serializer.validated_data['tasks'])
issue.save()
return Response({'status': 'issue created'})
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
我现在只有以下错误:
File "/views.py", line 32, in create
issue = Issue(title='test', tasks=serializer.validated_data['tasks'])
KeyError: 'tasks'
事实上,似乎serializer.validated_data没有任务键。我错过了定义我的序列化程序或我的create()的东西。
答案 0 :(得分:0)
您在tasks
中将read_only
标记为IssueSerializer
。这就是为什么您无法在tasks
中找到validated_data
密钥的原因。