简体   繁体   English

如何在 DRF 中保存对象列表

[英]How to save list of objects in DRF

I am new to django. I have following model:我是 django 的新手。我有以下 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 如下所示:

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.我的任务是打一个API,它会保存所有员工的数据,而不是单独保存员工的数据。 In the current implementation, each employee will have to hit the API separately to save the data in database.在目前的实施中,每个员工都必须分别拨打 API 才能将数据保存在数据库中。 Each employee will select team first, as one employee can be a part of multiple team.每个员工将 select 团队首先,因为一个员工可以成为多个团队的一部分。 We will save a list of objects.我们将保存一个对象列表。 Any leads on how to do it?关于如何做的任何线索?

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 https://www.django-rest-framework.org/api-guide/serializers/#customizing-multiple-create

Django provides bulk_create method for achieving that. Django 提供了用于实现该目的的 bulk_create 方法。

For example you can put the below function in your appropriate class in viewset:例如,您可以将以下 function 放入视图集中相应的 class 中:

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)

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM