如何在REST中发布多个条目

时间:2018-06-12 10:33:54

标签: python django rest

我正在构建REST API,用于存储人员的姓名,工资和费用。如何同时发布多个人的数据,如数组?

这是我的serializers.py文件

from rest_framework import serializers
from .models import Bucketlist


class BucketlistSerializer(serializers.ModelSerializer):
    class Meta:
        model = Bucketlist
        fields = ('id','name', 'date_created', 'salary','Expenditure')
        read_only_fields = ('date_created',)

这是我的views.py文件

screenshot of views.py

2 个答案:

答案 0 :(得分:0)

保存

时,您应该在序列化程序中使用(many = True)
data = BucketlistSerializer(data = your_post_array,many=True)
if data.is_valid():
   data.save()

将此添加到您的视图

    def get_serializer(self, *args, **kwargs):

        if isinstance(kwargs.get('data', {}), list):
           kwargs['many'] = True
        return super("your view class name ", self).get_serializer(*args, **kwargs)

用于功能基础视图

@api_view(['GET','POST'])
   def somefunction(request):



    if request.method == 'POST':
       data = BucketlistSerializer(data = request.data["key_for_data"], many=True)
       if data.is_valid():
          data.save()
          return(data.data)
    return(data.errors)

发布数据将是:{" key_for_data":[{},{}]

答案 1 :(得分:0)

str()在您的视图中构建queryset时提供Django属性。请看看: Multiple objects in serializer