class CreateModelMixin:
"""
1. 接收前台数据,前天的序列化对象,request.data是 QueryDict
如:
2. 验证序列化数据的有效性
3. 保存数据
4. 获得请求头
5. 返回状态
Create a model instance.
"""
def create(self, request, *args, **kwargs):
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)
def perform_create(self, serializer):
serializer.save()
def get_success_headers(self, data):
try:
return {'Location': str(data[api_settings.URL_FIELD_NAME])}
except (TypeError, KeyError):
return {}
class ListModelMixin:
"""
1. 获取 queryset ,通过 filter_queryset 进行过滤筛选
2. 对过滤筛选后的 queryset 进行分页,返回分页对象
3. 序列化,并返回序列化的数据
传入一个queryset,分别过滤,分页,序列化
List a queryset.
"""
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
# 分页
page = self.paginate_queryset(queryset)
# 这个是分页的序列化
if page is not None:
serializer = self.get_serializer(page, many=True)
# 下面是分页返回的额外结果
return self.get_paginated_response(serializer.data)
# 这个是不分页的序列化
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
class RetrieveModelMixin:
"""
获取对象,序列化
Retrieve a model instance.
"""
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
return Response(serializer.data)
class UpdateModelMixin:
"""
更新:
1. 获取 kwargs 字典中 partial 的值,如果没有,则返回False,有,则返回值
2. 获取单个对象
3. 通过序列化,获取单个对象的序列化对象
4. 判断序列化对象的有效性
5. 更新数据
Update a model instance.
"""
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
if getattr(instance, '_prefetched_objects_cache', None):
# If 'prefetch_related' has been applied to a queryset, we need to
# forcibly invalidate the prefetch cache on the instance.
instance._prefetched_objects_cache = {}
return Response(serializer.data)
def perform_update(self, serializer):
serializer.save()
def partial_update(self, request, *args, **kwargs):
kwargs['partial'] = True
return self.update(request, *args, **kwargs)
class DestroyModelMixin:
"""
删除:
1. 获取单个对象
2. 删除对象
Destroy a model instance.
"""
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
self.perform_destroy(instance)
return Response(status=status.HTTP_204_NO_CONTENT)
def perform_destroy(self, instance):
instance.delete()