0

我正在研究 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 对象列表?

4

1 回答 1

0

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

这在 django rest 框架文档中提到这里

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

资料来源: 如何使用 Django Rest Framework 创建多个模型实例?

于 2015-09-24T10:30:48.307 回答