0

I am working on REST API in Django.

Here is my view:

if request.method == 'GET':
    print "In get*****************"
    print "Request",request
    queryset = Beer.objects.all()
    serializer = BeerSerializer(queryset, many=True)
    return Response(serializer.data)

elif request.method == 'POST':
   print "In get*****************"
   print "Request",request.data
   serializer = FosterSerializer(data=request.data)
   if serializer.is_valid():
     serializer.save()
     return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

It is working fine with

curl -X POST http://192.168.2.241:8080/beers/ \
  -d '{"beer_type": "blond", "brand": "Foster" ,"ml": "6000"}' \
  -H "Content-Type: application/json"

but not working with

curl -X POST http://192.168.2.241:8080/beers/ \
  -d '[{"beer_type": "Mild1", "brand": "Foster" ,"ml": "199"},{"beer_type": "Mild", "brand": "Foster" ,"ml": "2"}]' \
  -H "Content-Type: application/json"

How can I process a list of JSON objects?

Ashish Kumar Verma
  • 1,322
  • 1
  • 13
  • 21
  • possible duplicate of [How do I create multiple model instances with Django Rest Framework?](http://stackoverflow.com/questions/14666199/how-do-i-create-multiple-model-instances-with-django-rest-framework) – Audrius Kažukauskas Sep 24 '15 at 11:08

1 Answers1

0

I think you looking for creating multiple objects in a single request. If you pass many=True when instantiating the serializer class for a model, it can then accept multiple objects.

This is mentioned here in the django rest framework docs

class FosterSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
    many = kwargs.pop('many', True)
    super(FosterSerializer, self).__init__(many=many, *args, **kwargs)

class Meta:
    model = Beer
    fields = ('loads', 'of', 'fields', )

Source : How do I create multiple model instances with Django Rest Framework?

Community
  • 1
  • 1
Sachin Gupta
  • 394
  • 3
  • 12