上一部分代码在序列化部分
类继承顺序
############### mixins.py ################
# 类中调用的方法均在 GenericAPIView 类中实现,所以下列类需要结合 GenericAPIView 使用
class ListModelMixin(object) # 查看继承类def list(self, request, *args, **kwargs)class CreateModelMixin(object) # 添加继承类def create(self, request, *args, **kwargsclass RetrieveModelMixin(object) # 查看单条继承类def retrieve(self, request, *args, **kwargs)class UpdateModelMixin(object) # 更新单条继承类def update(self, request, *args, **kwargs)class DestroyModelMixin(object) # 删除单条继承类def destroy(self, request, *args, **kwargs)############### generics.py ###############
class GenericAPIView(views.APIView)pass # 这个是懒得写,主要结合上边的使用class ListCreateAPIView(mixins.ListModelMixin,mixins.CreateModelMixin,GenericAPIView):def get(self, request, *args, **kwargs):return self.list(request, *args, **kwargs)def post(self, request, *args, **kwargs):return self.create(request, *args, **kwargs)class RetrieveUpdateAPIView(mixins.RetrieveModelMixin,mixins.UpdateModelMixin,GenericAPIView):def get(self, request, *args, **kwargs):return self.retrieve(request, *args, **kwargs)def put(self, request, *args, **kwargs):return self.update(request, *args, **kwargs)def patch(self, request, *args, **kwargs):return self.partial_update(request, *args, **kwargs)
)############### viewsets.py ###############
class ModelViewSet(mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,mixins.ListModelMixin,GenericViewSet)pass # 这个是真passclass GenericViewSet(ViewSetMixin, generics.GenericAPIView):pass # 这个也是真passclass ViewSetMixin(object):def as_view(cls, actions=None, **initkwargs)def view(request, *args, **kwargs):def initialize_request(self, request, *args, **kwargs):
不使用使用混合(mixins)
自己重构get,put等函数,全部手写,代码重复率很高:
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from django.shortcuts import HttpResponse
from django.core import serializers
from rest_framework import serializersclass BookSerializers(serializers.ModelSerializer):class Meta:model=Bookfields="__all__"#depth=1class PublshSerializers(serializers.ModelSerializer):class Meta:model=Publishfields="__all__"depth=1class BookViewSet(APIView):def get(self,request,*args,**kwargs):book_list=Book.objects.all()# 文本类型,这个是和上面的连接有关,后面的参数context,HyperlinkedIdentityField,这个是设置了连接的时候,进行的操作bs=BookSerializers(book_list,many=True,context={'request': request}) return Response(bs.data)def post(self,request,*args,**kwargs):print(request.data)bs=BookSerializers(data=request.data,many=False)if bs.is_valid():print(bs.validated_data)bs.save()return Response(bs.data)else:return HttpResponse(bs.errors)class BookDetailViewSet(APIView):def get(self,request,pk):book_obj=Book.objects.filter(pk=pk).first()bs=BookSerializers(book_obj,context={'request': request})return Response(bs.data)def put(self,request,pk):book_obj=Book.objects.filter(pk=pk).first()bs=BookSerializers(book_obj,data=request.data,context={'request': request})if bs.is_valid():bs.save()return Response(bs.data)else:return HttpResponse(bs.errors)class PublishViewSet(APIView):def get(self,request,*args,**kwargs):publish_list=Publish.objects.all()bs=PublshSerializers(publish_list,many=True,context={'request': request})return Response(bs.data)def post(self,request,*args,**kwargs):bs=PublshSerializers(data=request.data,many=False)if bs.is_valid():# print(bs.validated_data)bs.save()return Response(bs.data)else:return HttpResponse(bs.errors)class PublishDetailViewSet(APIView):def get(self,request,pk):publish_obj=Publish.objects.filter(pk=pk).first()bs=PublshSerializers(publish_obj,context={'request': request})return Response(bs.data)def put(self,request,pk):publish_obj=Publish.objects.filter(pk=pk).first()bs=PublshSerializers(publish_obj,data=request.data,context={'request': request})if bs.is_valid():bs.save()return Response(bs.data)else:return HttpResponse(bs.errors)
第一代:继承mixin类编写视图
继承mixins的ListModelMixin,CreateModelMixin等类
from rest_framework import mixins
from rest_framework import genericsclass BookViewSet(mixins.ListModelMixin, # 查看继承类mixins.CreateModelMixin, # 添加继承类generics.GenericAPIView):queryset = Book.objects.all() # 数据库serializer_class = BookSerializers # 序列化类def get(self, request, *args, **kwargs):return self.list(request, *args, **kwargs)def post(self, request, *args, **kwargs):return self.create(request, *args, **kwargs)class BookDetailViewSet(mixins.RetrieveModelMixin, # 查看单条继承类mixins.UpdateModelMixin, # 更新单条继承类mixins.DestroyModelMixin, # 删除单条继承类generics.GenericAPIView):queryset = Book.objects.all()serializer_class = BookSerializersdef get(self, request, *args, **kwargs):return self.retrieve(request, *args, **kwargs)def put(self, request, *args, **kwargs):return self.update(request, *args, **kwargs)def delete(self, request, *args, **kwargs):return self.destroy(request, *args, **kwargs)
第二代:使用通用的基于类的视图
通过使用mixin类,我们使用更少的代码重写了这些视图,但我们还可以再进一步。REST框架提供了一组已经混合好(mixed-in)的通用视图,我们可以使用它来简化我们的views.py
模块。
from rest_framework import mixins
from rest_framework import genericsclass BookViewSet(generics.ListCreateAPIView):queryset = Book.objects.all()serializer_class = BookSerializersclass BookDetailViewSet(generics.RetrieveUpdateDestroyAPIView):queryset = Book.objects.all()serializer_class = BookSerializersclass PublishViewSet(generics.ListCreateAPIView):queryset = Publish.objects.all()serializer_class = PublshSerializersclass PublishDetailViewSet(generics.RetrieveUpdateDestroyAPIView):queryset = Publish.objects.all()serializer_class = PublshSerializers
第三代:viewsets.ModelViewSet
urls.py:
url(r'^books/$', views.BookViewSet.as_view({"get":"list","post":"create"}),name="book_list"),
url(r'^books/(?P<pk>\d+)$', views.BookViewSet.as_view({'get': 'retrieve','put': 'update','patch': 'partial_update','delete': 'destroy'}),name="book_detail"),
views.py:
class BookViewSet(viewsets.ModelViewSet):queryset = Book.objects.all()serializer_class = BookSerializers
终极版
urls.py同上
views.py
from rest_framework.routers import DefaultRouterrouter = DefaultRouter() # 实例化
router.register(r'school', views.SchoolView) # 注册
urlpatterns += router.urls # 在urlpatterns中添加