如何处理包含JSON对象列表的请求

时间:2015-09-23 13:51:28

标签: python django django-rest-framework django-jsonfield

我正在使用Django中的REST API。

以下是我的观点:

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)

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

但不使用

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"

如何处理JSON对象列表?

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找在单个请求中创建多个对象。 如果在为模型实例化序列化程序类时传递many = True,则它可以接受多个对象。

这在django rest framework docs中提到here

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', )

资料来源: How do I create multiple model instances with Django Rest Framework?