Django rest framework: Insert multiple objects in one post request

后端 未结 1 2034
刺人心
刺人心 2021-02-06 17:39

I am using DRF for my API backend. I need to insert multiple objects into one post request. I saw so many tutorials, as well How do I create multiple model instances with Django

1条回答
  •  既然无缘
    2021-02-06 18:37

    rollback serializer to your default

    class SaleUserSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = SaleUser
            fields = ('id', 'comment', 'creation_date', 'modification_date', 'last_user', 'user', 'sale', 'user_sale_type')
    

    and override view to it:

    from rest_framework.response import Response    
    
    class SaleUserViewSet(ModelViewSet):
        queryset = SaleUser.objects.all()
        serializer_class = SaleUserSerializer
    
        def create(self, request, *args, **kwargs):
            data = request.data.get("items") if 'items' in request.data else request.data
            many = isinstance(data, list)
            print (data, many)
            serializer = self.get_serializer(data=data, many=many)
            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)
    

    0 讨论(0)
提交回复
热议问题