多种view视图和序列化--django2

 

models.py
 1 from django.db import models
 2 
 3 # Create your models here.
 4 class Idc(models.Model):
 5     name    = models.CharField("机房名称",max_length=32)
 6     address = models.CharField("机房地址",max_length=256)
 7     phone   = models.CharField("联系人",max_length=15)
 8     email   = models.EmailField("邮件地址",default="null")
 9     letter  = models.CharField("IDC简称",max_length=5)
10 
11     def __str__(self):
12         return self.name
13 
14     class Meta:
15         db_table = 'resources_idc'
models.py

serializers.py
 1 from rest_framework import serializers
 2 from .models import Idc
 3 
 4 class IdcSerializer(serializers.Serializer):
 5     """
 6     Idc 序列化类
 7     """
 8     id          = serializers.IntegerField(read_only=True)
 9     name        = serializers.CharField(required=True, max_length=32)
10     address     = serializers.CharField(required=True, max_length=256)
11     phone       = serializers.CharField(required=True, max_length=15)
12     email       = serializers.EmailField(required=True)
13     letter      = serializers.CharField(required=True, max_length=5)
14 
15     #必须有create,才能使用save(), data={...}   a=IdcSerializer(data=data)    a.save()
16     def create(self, validated_data):
17         return Idc.objects.create(**validated_data)
18     def update(self, instance, validated_data):
19       instance.name = validated_data.get("name", instance.name)
20       instance.address = validated_data.get("address", instance.address)
21       instance.phone = validated_data.get("phone", instance.phone)
22       instance.email = validated_data.get("email", instance.email)
23       instance.save()
24       return instance
serializers.py

 

 

版本一 :APIView

自己写get、post等方法

urlpatterns = [
    url("^$", views.api_root),
    url("^idcs/$", views.IdcList.as_view(), name="idc-list"),
    url("^idcs/(?P<pk>[0-9]+)/$", views.IdcDetail.as_view(), name="idc_detail")
]
urlpatterns = format_suffix_patterns(urlpatterns)
from rest_framework.views import APIView
from django.http import Http404

class IdcList(APIView):
    def get(self, request, format=None):
        queryset = Idc.objects.all()
        serializer = IdcSerializer(queryset, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = IdcSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)


class IdcDetail(APIView):

    def get_object(self, pk):
        try:
            return Idc.objects.get(pk=pk)
        except Idc.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        idc = self.get_object(pk)
        serializer = IdcSerializer(idc)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        idc = self.get_object(pk)
        serializer = IdcSerializer(idc, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND)

    def delete(self, request, pk, format=None):
        idc = self.get_object(pk)
        idc.delete()
        return HttpResponse(status=status.HTTP_204_NO_CONTENT)

 

 

 

版本二:使用混合类(generics.GenericAPIView+mixins.RetrieveModelMixin)实现

需要自己重复写get、post方法,因为ListModelMixin没有写get方法

from rest_framework import generics 
from rest_framework import mixins

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(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(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)

 

版本三:viewset(viewsets.GenericViewSet+mixins)扩展实现

 

将所有请求用一个class实现,如:GenericViewSet+ListModelMixin

get请求绑定到list之上,post绑定到create

##########################  版本六   ############################
from rest_framework import viewsets

class IdcListViewset(viewsets.GenericViewSet,
                     mixins.ListModelMixin,
                     mixins.RetrieveModelMixin,
                     mixins.DestroyModelMixin,
                     mixins.UpdateModelMixin,
                     mixins.CreateModelMixin):
    queryset = Idc.objects.all()
    serializer_class = IdcSerializer
urls.py绑定参数:
idc_list = views.IdcListViewset.as_view({
    "get": "list",
    "post": "create"
})

idc_detail = views.IdcListViewset.as_view({
    "get": "retrieve",
    "put": "update",
    "delete": "destroy"
})
urlpatterns = [
    #url("^$", views.api_root),
    url("^idcs/$", idc_list, name="idc-list"),#此时,url中不需要再加as_view()了
    url("^idcs/(?P<pk>[0-9]+)/$", idc_detail, name="idc_detail")
]

或者用router实现自动绑定get 和list,create 和 post等等

from rest_framework.routers import DefaultRouter  # 导入
from django.urls import path

#实例化router
router
= DefaultRouter()
# 注册idc
router.register(r
'idc', IdcListViewset, base_name="idcs")

urlpatterns = [ # router的path路径 path('', include(router.urls)),
]

 

 

 

 

版本四:使用高级混合(generics.ListCreateAPIView等)实现

 

父类包含具体请求方式,如:ListCreateAPIView包括了get

 

 

urlpatterns = [
    url("^$", views.api_root),
    url("^idcs/$", views.IdcList_V5.as_view(), name="idc-list"),
    url("^idcs/(?P<pk>[0-9]+)/$", views.IdcDetail_V5.as_view(), name="idc_detail")
]
urlpatterns = format_suffix_patterns(urlpatterns)

 

from rest_framework import generics

class IdcList_V5(generics.ListCreateAPIView):#包括查找和创建 queryset = Idc.objects.all() serializer_class = IdcSerializer
class IdcDetail_V5(generics.RetrieveUpdateDestroyAPIView): #包括 详细查找 、更新和删除
queryset = Idc.objects.all()
serializer_class = IdcSerializer

 

 

 

 

版本五: ModelViewSet(router)实现:

整合:ModelViewSet包括所有方法
##########################  版本七   ############################
from rest_framework.routers import  DefaultRouter

route = DefaultRouter()
route.register("idcs", views.IdcViewset_v7)
urlpatterns = [
    url(r'^', include(route.urls))
]
class IdcViewset_v7(viewsets.ModelViewSet):
    queryset = Idc.objects.all()
    serializer_class = IdcSerializer

 

posted @ 2019-05-05 14:50  凯文队长  阅读(535)  评论(0编辑  收藏  举报