django 如何在DRF中保存对象列表

0g0grzrc  于 2023-01-10  发布在  Go
关注(0)|答案(3)|浏览(183)

我是新来的django。我有以下模型:

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

序列化程序类如下所示:

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

视图集是这样的:

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

我的任务是打一个单一的API,将保存所有员工的数据,而不是分别保存员工的数据。在目前的实施,每个员工将不得不打API分别保存数据库中的数据。每个员工将选择团队第一,因为一个员工可以是多个团队的一部分。我们将保存一个对象列表。任何线索如何做到这一点?

eqqqjvef

eqqqjvef1#

尝试在请求正文中传递一个数据列表。您需要修改序列化程序并重写create以进行批量创建和保存数据。您可以按照下面的步骤操作。https://www.django-rest-framework.org/api-guide/serializers/#customizing-multiple-create

eagi6jfj

eagi6jfj2#

Django提供了bulk_create方法来实现这一点。
例如,您可以将以下函数放入视图集中相应的类中:

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

wmtdaxz33#

您可以重写create方法。

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)

相关问题