Django Rest Framework 使用mixins模块优化序列化接口 (get-post-put-delete)

继承《Django Rest Framework 序列化接口(PUT与Delete)设计 (前期版)!    》代码

修改views.py代码

'''3.视图组件优化方式一:使用mixins优化'''
#导入mixins模块
from rest_framework.mixins import (
    CreateModelMixin,  # 增删改查复
    DestroyModelMixin,
    UpdateModelMixin,
    ListModelMixin,
    RetrieveModelMixin
)
#导入已经写好的序列化类
from .serizlizer import BookSerizlizer
#导入GenericAPIView,它继承APIView
from rest_framework.generics import GenericAPIView


class BookView(ListModelMixin, CreateModelMixin, GenericAPIView):
    #固定下来的类变量
    queryset = models.Book.objects.all()
    serializer_class = BookSerizlizer

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

#对单条数据做修改urls.py :"re_path(r'book/(?P<pk>\d+)/$',views.BookFilterView.as_view())",此处匹配中写PK它会自动识别
class BookFilterView(RetrieveModelMixin, GenericAPIView, DestroyModelMixin, UpdateModelMixin):
    queryset = models.Book.objects.all()
    serializer_class = BookSerizlizer

    def get(self, request, *args, **kwargs, ):
        return self.retrieve(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request,  *args, **kwargs)

    def put(self, request, *args, **kwargs, ):
        return self.update(request,*args, **kwargs, )
views.py
from django.contrib import admin
from django.urls import path,re_path
from books import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('book/',views.BookView.as_view()),
    #对于单条指定数据的put,get,delete,post方法定义的url
    re_path(r'book/(?P<pk>\d+)/$',views.BookFilterView.as_view())
]

 

posted @ 2020-02-20 11:10  y0um  阅读(293)  评论(0编辑  收藏  举报

新人优惠服务器