Django rest PUT请求序列化器无法使用外键更新模型

时间:2017-07-23 19:24:54

标签: django django-rest-framework

我有两个模型如下:

class Task(models.Model):
    user = models.ForeignKey(User, blank=True)
    what_task = models.CharField(max_length=100, )

    #This helps to print in admin interface
    def __str__(self):
        return u"%s" % (self.what_task)


class Step(models.Model):
    task = models.ForeignKey(Task, related_name='steps', on_delete=models.CASCADE, )
    what_step = models.CharField(max_length=50, blank=True, )

    #This helps to print in admin interface
    def __str__(self):
        return u"%s" % (self.what_step)

我写过序列化器:

class StepSerializer(serializers.ModelSerializer):
    class Meta:
        model = Step
        exclude = ('task',)

class TaskSerializer(serializers.ModelSerializer):
    steps = StepSerializer(many=True)
    class Meta:
        model = Task
        fields = '__all__'


    def create(self, validated_data):
        steps_data = validated_data.pop('steps')
        task = Task.objects.create(**validated_data)
        for step_data in steps_data:
            Step.objects.create(task=task, **step_data)
        return task 

    def update(self, instance, validated_data):
        steps_data = validated_data.pop('steps')

        instance.what_task = validated_data.get('what_task', instance.what_task)
        instance.how_often = validated_data.get('how_often', instance.how_often)
        instance.how_important = validated_data.get('how_important', instance.how_important)
        instance.why_perform = validated_data.get('why_perform', instance.why_perform)
        instance.why_important = validated_data.get('why_important', instance.why_important)
        instance.possible_improvement = validated_data.get('possible_improvement', instance.possible_improvement)
        instance.existing_solutions = validated_data.get('existing_solutions', instance.existing_solutions)
        instance.how_important_improvement = validated_data.get('how_important_improvement', instance.how_important_improvement)
        instance.advantages_of_improvement = validated_data.get('advantages_of_improvement', instance.advantages_of_improvement)

        instance.save()
        for step_data in steps_data:
            Step.objects.update(task=task, **step_data)
        return instance 

我的观点:

@api_view(['GET', 'POST'])
def task_list(request):
    """
    List all tasks, or create a new task.
    """
    if request.method == 'GET':
        print(request.user)
        tasks = Task.objects.filter(user=request.user.id)
        serializer = TaskSerializer(tasks, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = TaskSerializer(data=request.data)
        print(request.data)
        if serializer.is_valid():
            serializer.save(user=request.user)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(
                serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'PUT', 'DELETE'])
def task_detail(request, id):
    """
    Get, udpate, or delete a specific task
    """
    try:
        task = Task.objects.get(id=id)
    except Task.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = TaskSerializer(task)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = TaskSerializer(task, data=request.data)
        if serializer.is_valid():
            serializer.save(user=request.user)
            return Response(serializer.data)
        else:
            return Response(
                serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        task.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

我的 GET POST 请求工作正常(视图中的第一个功能),我的任务和相关步骤是在单个请求中创建的,但 PUT 请求是错误的,我不确定我是否正确更新了步骤;如果我从serializer for循环注释掉,则任务会成功更新。

我应该修改什么以及如何修改以便我可以使用相关步骤更新特定任务?

1 个答案:

答案 0 :(得分:1)

在for循环中,您更新每个现有任务(在update内,您设置新值):

Step.objects.update(task=task, **step_data)

相反,在循环之前,您应该删除该任务的所有步骤并创建新步骤:

...
    Step.objects.filter(task=instance).delete()
    for step_data in steps_data:
        Step.objects.create(task=instance, **step_data)
...

更有效的方法是找到validated_data中不存在的所有步骤(基于id)并删除它们,使用id更新步骤,创建没有id的步骤。