Django REST framework post array of objects

后端 未结 5 674
挽巷
挽巷 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:28

    If you want to post a list you have to pass in JSON encoded data.

    headers = {"Token": "35754sr7cvd7ryh454"}
    
    recipients = [{'name': 'Ut est sed sed ipsa', 
                   'email': 'dogoka@mailinator.com', 
                   'group': 'signers'},
                  {'name': 'Development Ltda.', 
                   'email': 'test@test.com',
                   'group': 'signers'}
                 ]
    
    requests.post(url, json=recipients, headers=headers)
    

    requests.post(url, json=recipients, headers=headers)

    Use json keyword argument (not data) so the data is encoded to JSON and the Content-Type header is set to application/json.

    By default, Django Rest Framework assumes you are passing it a single object. To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.

    To do it, you'll have to override the .create() method of your view:

    def create(self, request, *args, **kwargs):
        many = True if isinstance(request.data, list) else False
    
        serializer = self.get_serializer(data=request.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)
    

    Documentation: https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-multiple-objects

提交回复
热议问题