我想使用Django Rest Framework通过一个API调用来保存和更新多个实例。例如,假设我有一个“教室”模型,可以有多个“老师”。如果我想创建多位老师,然后更新他们的所有教室编号,我该怎么做?我需要为每个老师进行API调用吗?
我知道目前我们无法保存嵌套模型,但是我想知道是否可以在教师级别保存它。谢谢!
Answers:
我知道这是在不久前被问到的,但是我在试图自己解决这个问题时就发现了。
事实证明,如果你通过了 many=True
在实例化模型的序列化器类时,则它可以接受多个对象。
这是提到这里django rest框架文档中
就我而言,我的观点如下所示:
class ThingViewSet(viewsets.ModelViewSet):
"""This view provides list, detail, create, retrieve, update
and destroy actions for Things."""
model = Thing
serializer_class = ThingSerializer
我并不是真的想写一个样板代码只是为了直接控制序列化器和pass的实例化many=True
,所以在我的序列化器类中,我改写了__init__
:
class ThingSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
many = kwargs.pop('many', True)
super(ThingSerializer, self).__init__(many=many, *args, **kwargs)
class Meta:
model = Thing
fields = ('loads', 'of', 'fields', )
将数据以以下格式发布到该视图的列表URL:
[
{'loads':'foo','of':'bar','fields':'buzz'},
{'loads':'fizz','of':'bazz','fields':'errrrm'}
]
使用这些详细信息创建了两个资源。很好
我得出的结论与Daniel Albarral相似,但这是一个更简洁的解决方案:
class CreateListModelMixin(object):
def get_serializer(self, *args, **kwargs):
""" if an array is passed, set serializer to many """
if isinstance(kwargs.get('data', {}), list):
kwargs['many'] = True
return super(CreateListModelMixin, self).get_serializer(*args, **kwargs)
这是另一种解决方案,您不需要重写序列化器__init__
方法。只需重写视图的(ModelViewSet)'create'
方法即可。通知many=isinstance(request.data,list)
。在这里,many=True
当您发送要创建的对象数组时,以及False
仅发送一个对象时。这样,您可以同时保存项目和列表!
from rest_framework import status, viewsets
from rest_framework.response import Response
class ThingViewSet(viewsets.ModelViewSet):
"""This view snippet provides both list and item create functionality."""
#I took the liberty to change the model to queryset
queryset = Thing.objects.all()
serializer_class = ThingSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data, many=isinstance(request.data,list))
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
transaction.atomic()
块以确保添加了所有元素
Expected a dictionary, but got list.
可接受答案中的错误,这个错误为我解决了。谢谢。
我不太想知道如何将request.DATA从字典转换为数组-这对Tom Manterfield解决方案的工作能力造成了限制。这是我的解决方案:
class ThingSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
many = kwargs.pop('many', True)
super(ThingSerializer, self).__init__(many=many, *args, **kwargs)
class Meta:
model = Thing
fields = ('loads', 'of', 'fields', )
class ThingViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet ):
queryset = myModels\
.Thing\
.objects\
.all()
serializer_class = ThingSerializer
def create(self, request, *args, **kwargs):
self.user = request.user
listOfThings = request.DATA['things']
serializer = self.get_serializer(data=listOfThings, files=request.FILES, many=True)
if serializer.is_valid():
serializer.save()
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED,
headers=headers)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
然后在客户端上运行与此等效的命令:
var things = {
"things":[
{'loads':'foo','of':'bar','fields':'buzz'},
{'loads':'fizz','of':'bazz','fields':'errrrm'}]
}
thingClientResource.post(things)
many=True
在get_serializer
通话中
我认为尊重该框架的最佳架构的最佳方法是创建一个像这样的mixin:
class CreateListModelMixin(object):
def create(self, request, *args, **kwargs):
"""
Create a list of model instances if a list is provides or a
single model instance otherwise.
"""
data = request.data
if isinstance(data, list):
serializer = self.get_serializer(data=request.data, many=True)
else:
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED,
headers=headers)
然后,您可以像这样覆盖ModelViewSet的CreateModelMixin:
class <MyModel>ViewSet(CreateListModelMixin, viewsets.ModelViewSet):
...
...
现在在客户端中,您可以像这样工作:
var things = [
{'loads':'foo','of':'bar','fields':'buzz'},
{'loads':'fizz','of':'bazz','fields':'errrrm'}
]
thingClientResource.post(things)
要么
var thing = {
'loads':'foo','of':'bar','fields':'buzz'
}
thingClientResource.post(thing)
编辑:
正如罗杰·柯林斯(Roger Collins)在回应中所建议的那样,重写get_serializer方法比“创建”方法更聪明。
你可以简单地覆盖get_serializer
法在APIView并传递many=True
到get_serializer
像这样的基础视角:
class SomeAPIView(CreateAPIView):
queryset = SomeModel.objects.all()
serializer_class = SomeSerializer
def get_serializer(self, instance=None, data=None, many=False, partial=False):
return super(SomeAPIView, self).get_serializer(instance=instance, data=data, many=True, partial=partial)
data
,必须.is_valid()
在尝试访问序列化.data
表示形式之前调用关键字参数。您应该.is_valid()
先呼叫,或者先访问.initial_data
。
from rest_framework.fields import empty def get_serializer(self, instance=None, data=empty, many=False, partial=False): return super(SomeAPIView, self).get_serializer(instance=instance, data=data, many=True, partial=partial)
Django REST Framework文档中的“通用视图”页面指出ListCreateAPIView通用视图“用于读写端点来表示模型实例的集合”。
那就是我开始寻找的地方(实际上,因为我们很快也会在我们的项目中需要此功能,所以我要去找它)。
另请注意,“通用视图”页面上的示例恰好使用ListCreateAPIView
。
我想出了一个简单的例子 post
Serializers.py
from rest_framework import serializers
from movie.models import Movie
class MovieSerializer(serializers.ModelSerializer):
class Meta:
model = Movie
fields = [
'popularity',
'director',
'genre',
'imdb_score',
'name',
]
Views.py
from rest_framework.response import Response
from rest_framework import generics
from .serializers import MovieSerializer
from movie.models import Movie
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
class MovieList(generics.ListCreateAPIView):
queryset = Movie.objects.all().order_by('-id')[:10]
serializer_class = MovieSerializer
permission_classes = (IsAuthenticated,)
def list(self, request):
queryset = self.get_queryset()
serializer = MovieSerializer(queryset, many=True)
return Response(serializer.data)
def post(self, request, format=None):
data = request.data
if isinstance(data, list): # <- is the main logic
serializer = self.get_serializer(data=request.data, many=True)
else:
serializer = self.get_serializer(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)
这些行是多实例的实际逻辑-
data = request.data
if isinstance(data, list): # <- is the main logic
serializer = self.get_serializer(data=request.data, many=True)
else:
serializer = self.get_serializer(data=request.data)
当我们发送数据时,它会list
像这样-
[
{
"popularity": 84.0,
"director": "Stanley Kubrick",
"genre": [
1,
6,
10
],
"imdb_score": 8.4,
"name": "2001 : A Space Odyssey"
},
{
"popularity": 84.0,
"director": "Stanley Kubrick",
"genre": [
1,
6,
10
],
"imdb_score": 8.4,
"name": "2001 : A Space Odyssey"
}
]
我遇到的最简单的方法:
def post(self, request, *args, **kwargs):
serializer = ThatSerializer(data=request.data, many=isinstance(request.data, list))
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)