Home > OS >  Django multiple update Task at once
Django multiple update Task at once

Time:05-27

I have my Django website where i can have tasks created and subtasks under tasks i have mark complete option which is working fine i need them to be completed in batch like selecting multiple tasks at once and complete them.

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,
)
    

CodePudding user response:

You can use bulk_update

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

CodePudding user response:

I think you can change the path for bulk update.

In urls.py,

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

And in views.py, you can customize put method for update request.

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)
     

In frontend, when you update one object, the api url should be set like .../1/complete/.

When you update multiple objects, the api url can be .../1,2,3/complete/.

  • Related