我想通过一个 API 调用使用 Django Rest Framework 保存和更新多个实例。例如,假设我有一个可以有多个“教师”的“教室”模型。如果我想创建多个教师,然后更新他们所有的教室号码,我会怎么做?我是否必须为每位教师进行 API 调用?
我知道目前我们无法保存嵌套模型,但我想知道我们是否可以在教师级别保存它。谢谢!
我想通过一个 API 调用使用 Django Rest Framework 保存和更新多个实例。例如,假设我有一个可以有多个“教师”的“教室”模型。如果我想创建多个教师,然后更新他们所有的教室号码,我会怎么做?我是否必须为每位教师进行 API 调用?
我知道目前我们无法保存嵌套模型,但我想知道我们是否可以在教师级别保存它。谢谢!
我知道这是不久前有人问过的,但是我在自己尝试解决这个问题时发现了它。
事实证明,如果您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)
我无法完全弄清楚如何让 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)
我认为尊重框架提议架构的最佳方法是创建一个像这样的 mixin:
class CreateListModelMixin(object):
def create(self, request, *args, **kwargs):
"""
Create a list of model instances if a list is provided 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)
编辑:
正如罗杰柯林斯在他的回应中建议的那样,覆盖 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)
我想出了一个简单的例子post
序列化程序.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',
]
视图.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"
}
]
Django REST Framework 文档中的通用视图页面指出ListCreateAPIView通用视图“用于读写端点以表示模型实例的集合”。
这就是我开始寻找的地方(实际上我会去寻找,因为我们很快也会在我们的项目中需要这个功能)。
另请注意,Generic Views 页面上的示例恰好使用ListCreateAPIView
.
我遇到的最直接的方法:
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)