特点:
1)继承自object
2)Mixin不能单独使用,需要配合GenericAPIView使用
5个扩展类:
1)ListModelMixin:list
class ListModelMixin(object):
def list(self, request, *args, **kwargs):
"""封装获取一组数据通用代码"""
queryset = self.get_queryset()
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
2)CreateModelMixin:create
class CreateModelMixin(object):
def create(self, request, *args, **kwargs):
"""封装新增数据通用代码"""
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save() # 调用序列化器类中的create
return Response(serializer.data, status=status.HTTP_201_CREATED)
3)RetrieveModelMixin:retrieve
class RetrieveModelMixin(object):
def retrieve(self, request, *args, **kwargs):
"""封装获取指定数据的通用代码"""
instance = self.get_object()
serializer = self.get_serializer(instance)
return Response(serializer.data)
4)UpdateModelMixin:update
class UpdateModelMixin(object):
def update(self, request, *args, **kwargs):
"""封装更新指定数据的通用代码"""
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save() # 调用序列化器类中的update
return Response(serializer.data)
5)DestroyModelMixin:destroy
class DestroyModelMixin(object):
def destroy(self, request, *args, **kwargs):
"""封装删除指定数据的通用代码"""
instance = self.get_object()
instance.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
Mixin改写RestAPI接口
# views.py
from rest_framework.generics import GenericAPIView
from rest_framework import mixins
from rest_framework import status
from booktest.serializers import BookInfoSerializer
from booktest.models import BookInfo
# /books/
class BookListView(mixins.ListModelMixin,
mixins.CreateModelMixin,
GenericAPIView):
"""
获取所有图书、增加图书
"""
# 指定视图所使用的序列化器类
serializer_class = BookInfoSerializer
# 指定视图所使用的查询集
queryset = BookInfo.objects.all()
def get(self, request):
"""
获取所有的图书数据
"""
return self.list(request)
def post(self, request):
"""
新增一个图书数据
"""
return self.create(request)
# /books/(?P<pk>\d+)/
class BookDetailView(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
GenericAPIView):
"""
获取、修改、删除指定图书
"""
# 指定视图所使用的序列化器类
serializer_class = BookInfoSerializer
# 指定视图所使用的查询集
queryset = BookInfo.objects.all()
def get(self, request, pk):
"""
获取指定图书
"""
return self.retrieve(request, pk)
def put(self, request, pk):
"""
修改指定图书
"""
return self.update(request, pk)
def delete(self, request, pk):
"""
删除指定图书:
"""
return self.destroy(request, pk)