Home > Software design >  How to save list of objects in DRF
How to save list of objects in DRF

Time:01-09

I am new to django. I have following model:

class Standup(models.MOdel):
    team = models.ForeignKey("Team", on_delete=models.CASCADE)  
    standup_time = models.DateTimeField(auto_now_add=True)  
    employee = models.ForeignKey("Employee", on_delete=models.CASCADE)
    update_time = models.DateTimeField(auto_now_add=True)
    status = models.CharField(max_length=50)
    work_done_yesterday = models.TextField()
    work_to_do = models.TextField()
    blockers = models.TextField()

Serializer class looks like this:

class StandupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Standup
        fields = '__all__'  

Viewset is like this:

class StandupDetail(viewsets.ModelViewSet):
    queryset =  Standup.objects.all()
    serializer_class = StandupSerializer 

My task is to hit a single API which will save the data of all employees, instead of saving the data of employees separately. In the current implementation, each employee will have to hit the API separately to save the data in database. Each employee will select team first, as one employee can be a part of multiple team. We will save a list of objects. Any leads on how to do it?

CodePudding user response:

Try to pass a list of data in request body. You need to modify your serializer as well as override the create for bulk creation and saving of data. You can follow this. https://www.django-rest-framework.org/api-guide/serializers/#customizing-multiple-create

CodePudding user response:

Django provides bulk_create method for achieving that.

For example you can put the below function in your appropriate class in viewset:

def bulk_update_standup(self, request, *args, **kwargs):
    standup_list = request.data.get("standupList", [])
    qs = []
    for item in standup_list:
        serializer = StandupSerializer(data=item)
        standup_instance = Standup(**serializer.validated_data)
        qs.append(standup_instance)

    Standup.objects.bulk_create(qs)
    data = {"data": None, "message": "Saved Successfully"}
    return Response(data=data, status=status.HTTP_200_OK)

CodePudding user response:

You can override create method.

    def create(self, request, *args, **kwargs):
      if isinstance(request.data, list):
        serializer = self.get_serializer(data=request.data, many=True)
      else:
        serializer = self.get_serializer(data=request.data)
      serializer.is_valid(raise_exception=True)
      self.perform_create(serializer)
      headers = self.get_success_headers(serializer.data)
      return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
  • Related