View extended by six
effect:
Provides several back-end view (deletion of data resources has been checked) to achieve processing flow, if you need to write views belong to these five, you can view the code reuse through inheritance corresponding extension classes, reduce code I have written the amount.
This extension classes need to match five GenericAPIView parent class, because class methods to achieve five expansion serializer and database queries GenericAPIView provided need to call.
ListModelMixin
Extension class list view, there is provided list(request, *args, **kwargs)
method to quickly list view 200 returns a status code.
The data will Mixin list method for filtering and paging.
Source:
class ListModelMixin(object):
"""
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)
For example:
from rest_framework.mixins import ListModelMixin
class BookListView(ListModelMixin, GenericAPIView):
queryset = BookInfo.objects.all()
serializer_class = BookInfoSerializer
def get(self, request):
return self.list(request)
CreateModelMixin
There are two ways
Creating the view extension class that provides create(request, *args, **kwargs)
a method to quickly realize the resources to create a view, a successful return 201 status code.
If the sequence of the authentication failure of the data transmission of the front end, returns 400 an error.
Source:
class CreateModelMixin(object):
"""
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 {}
RetrieveModelMixin
Extension class detail view, there is provided retrieve(request, *args, **kwargs)
a method, it can be implemented quickly return to a present data object.
If so, return to 200, otherwise 404.
Source:
class RetrieveModelMixin(object):
"""
Retrieve a model instance.
"""
def retrieve(self, request, *args, **kwargs):
# 获取对象,会检查对象的权限
instance = self.get_object()
# 序列化
serializer = self.get_serializer(instance)
return Response(serializer.data)
For example:
class BookDetailView(RetrieveModelMixin, GenericAPIView):
queryset = BookInfo.objects.all()
serializer_class = BookInfoSerializer
def get(self, request, pk):
return self.retrieve(request)
UpdateModelMixin
Updated view expansion class provides update(request, *args, **kwargs)
methods, can be implemented quickly update an existing data object.
It also provides partial_update(request, *args, **kwargs)
methods may be implemented partial update.
200 successful return, when the data serializer check fails, returns 400 an error.
Source:
class UpdateModelMixin(object):
"""
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)
DestroyModelMixin
Delete View extension class is provided destroy(request, *args, **kwargs)
a method, it can be implemented quickly delete an existing data object.
The successful return of 204, 404 there is no return.
Source:
class DestroyModelMixin(object):
"""
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()
Content from: https://www.cnblogs.com/xiaoyuanqujing