6. 使用混合,mixins,

使用混合,代码就非常少了

初级版

视图层

from django.shortcuts import render
from .models import Idc
from .serializers import IdcSerializer

from rest_framework.decorators import api_view
from rest_framework import status
from rest_framework.response import Response

from rest_framework.reverse import reverse    

@api_view(["GET"])
def api_root(request,format=None,*args,**kwargs):
    return Response(
        {
            "idcs" : reverse("idcs-list",request=request,format=format)
        }
    )

from rest_framework import mixins,generics
class IdcList_V4(generics.GenericAPIView,
                 mixins.ListModelMixin,
                 mixins.CreateModelMixin):
    queryset = Idc.objects.all()
    serializer_class = IdcSerializer
    def get(self,request,*args,**kwargs):
        return self.list(self,request,*args,**kwargs)
    def post(self,request,*args,**kwargs):
        return self.create(self,request,*args,**kwargs)    
    
class IdcDetail_V4(generics.GenericAPIView,
                 mixins.RetrieveModelMixin,
                 mixins.UpdateModelMixin,
                 mixins.DestroyModelMixin,):
    queryset = Idc.objects.all()
    serializer_class = IdcSerializer
    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 delete(self,request,*args,**kwargs):
        return self.destroy(request,*args,**kwargs)  

路由层

### 版本四
urlpatterns = [
   url("^$",views.api_root),
   url("^idcs/$",views.IdcList_V4.as_view(),name="idcs-list"),
   url("^idcs/(?P[0-9]+)/$",views.IdcDetail_V4.as_view(),name="idc_detail"),
]
urlpatterns = format_suffix_patterns(urlpatterns)

高级版

### 版本五
urlpatterns = [
   url("^$",views.api_root),
   url("^idcs/$",views.IdcList_V5.as_view(),name="idcs-list"),
   url("^idcs/(?P[0-9]+)/$",views.IdcDetail_V5.as_view(),name="idc_detail"),
]
urlpatterns = format_suffix_patterns(urlpatterns)
###### 版本五,更简单的代码
from rest_framework import mixins,generics
class IdcList_V5(generics.ListCreateAPIView):
    queryset = Idc.objects.all()
    serializer_class = IdcSerializer
    
class IdcDetail_V5(generics.RetrieveDestroyAPIView):
    queryset = Idc.objects.all()
    serializer_class = IdcSerializer

你可能感兴趣的:(序列化,django)