Django REST framework post array of objects

后端 未结 5 643
挽巷
挽巷 2020-12-16 14:43

I am using Django REST framework for API and Angular SPA with Restangular to communicate with the API. Sometimes, I have to add more than one object using the API and I thin

5条回答
  •  庸人自扰
    2020-12-16 15:12

    Another example that supports posting an array as well as posting a single object. Might be useful for anyone else looking for such an example.

    class BookViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
        """
        ViewSet create and list books
    
        Usage single : POST
        {
            "name":"Killing Floor: A Jack Reacher Novel", 
            "author":"Lee Child"
        }
    
        Usage array : POST
        [{  
            "name":"Mr. Mercedes: A Novel (The Bill Hodges Trilogy)",
            "author":"Stephen King"
        },{
            "name":"Killing Floor: A Jack Reacher Novel", 
            "author":"Lee Child"
        }]
        """
        queryset = Book.objects.all()
        serializer_class = BookSerializer
        search_fields = ('name','author')
    
        def create(self, request, *args, **kwargs):
            """
            #checks if post request data is an array initializes serializer with many=True
            else executes default CreateModelMixin.create function 
            """
            is_many = isinstance(request.data, list)
            if not is_many:
                return super(BookViewSet, self).create(request, *args, **kwargs)
            else:
                serializer = self.get_serializer(data=request.data, many=True)
                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)
    

提交回复
热议问题