我正在构建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文件
答案 0 :(得分:0)
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