Home > Back-end >  Batch Complete Tasks in DRF
Batch Complete Tasks in DRF

Time:05-26

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)

CodePudding user response:

I think you need to create a function API view to implement this easily.

class TaskBulkUpdateSerializer(serializers.Serializer):
    task_ids = serializers.ListField(
        child = serializers.IntegerField())
    is_done = serializers.BooleanField()

And in views.py, you need to create bulk_update_tasks function.

from .serializers import TaskBulkUpdateSerializer
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from .models import Task, Subtask

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def bulk_update_tasks(request):
    serializer = TaskBulkUpdateSerializer(request.data)
    if serializer.is_valid():
        input_data = serializer.validated_data
        task_ids = input_data.get('task_ids')
        is_done = input_data.get('is_done')
        
        # check if all the tasks exist and all of them are owned by the user
        for task_id in task_ids:
            try:
                task = Task.objects.get(pk = task_id)                
                if task.done_by.id != request.user.id:
                    return Response(status = status.HTTP_400_BAD_REQUEST)
            except:
                return Response(status = status.HTTP_400_BAD_REQUEST)

        # if it's ok, then update
        Task.objects.filter(id__in = task_ids).update(is_done = is_done)

        # update subtasks
        if is_done:
            Subtask.objects.filter(subtask_of__id__in = task_ids).update(is_done = True)
        
        return Response(status = status.HTTP_200_OK)
    else:
        return Response(status = status.HTTP_400_BAD_REQUEST)
        

In urls.py, you need to add the api.

path('complete/bulk', bulk_update_task, name='task_bulk_update')
  • Related