Django 一次更新多个任务

Django multiple update Task at once

我有我的 Django 网站,我可以在其中创建任务和任务下的子任务我有标记完成选项,它工作正常我需要它们分批完成,比如一次选择多个任务并完成它们。

serializers.py:

class TaskCompleteSerializer(serializers.ModelSerializer):
     class Meta:
    model = Task
    fields = (
        'is_done',
    )

     def update(self, instance, validated_data):
         person = self.context['request'].user.person

         task_is_done = validated_data.get('is_done', False)

         if task_is_done:
            instance.subtasks.update(is_done=True)

         instance.is_done = task_is_done
         instance.done_by.set([person])
         instance.save()

         return instance

views.py:

class TaskUpdateAPIView(UpdateAPIView):
     permission_classes = " "
     serializer_class = TaskCompleteSerializer
     queryset = Task.objects.all()
     model = Task
     lookup_url_kwarg = 'task_id'

urls.py

path('<int:task_id>/complete/',views.TaskUpdateAPIView.as_view(), 
name='task_update'),

models.py

class Task(BaseModel):
    name = models.CharField(max_length=255)
    done_by = models.ManyToManyField(
    User,
    related_name='tasks_completed',
    blank=True,
    )
    is_done = models.BooleanField(default=False)

class Subtask(models.Model):
    name = models.CharField(max_length=255)
    subtask_of = models.ForeignKey(
    Task,
    related_name='subtasks',
    blank=True,
    null=True,
    on_delete=models.CASCADE,
)
    

您可以使用bulk_update

for task in tasks:
    task.is_done = True
Task.objects.bulk_update(tasks)

我想你可以更改批量更新的路径。

在urls.py,

path('<str:task_ids>/complete', views.TaskUpdateAPIView.as_view(), 
name='task_update'),

并且在views.py中,您可以自定义put更新请求的方法。

class TaskUpdateAPIView(UpdateAPIView):
    permission_classes = " "
    serializer_class = TaskCompleteSerializer
    queryset = Task.objects.all()
     
    def put(self, request, task_ids):
        id_array = task_ids.split(",")
        for id_item in id_array:
            try:
                task= Task.objects.get(pk=id_item)
                task_serializer = self.get_serializer(task, data = request.data)
                if task_serializer.is_valid():
                    task_serializer.save()
            except Member.DoesNotExist:
                continue
        return Response(status=status.HTTP_200_OK)
     

在前端,当您更新一个对象时,api url 应该设置为 .../1/complete/

当您更新多个对象时,api url 可以是 .../1,2,3/complete/