Django Rest框架3.4.0,ViewSet具有自定义create()和多对多关系

时间:2016-08-04 22:51:03

标签: python django django-rest-framework

我有以下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()的东西。

1 个答案:

答案 0 :(得分:0)

您在tasks中将read_only标记为IssueSerializer。这就是为什么您无法在tasks中找到validated_data密钥的原因。