Django框架之DRF 基于mixins来封装的视图详解

时间:2021-05-22

基础视图

示例环境搭建:新建一个Django项目,连接Mysql数据库,配置路由、视图函数、序列化单独创建py文件

# 配置路由from django.conf.urls import urlfrom django.contrib import adminfrom app01 import viewsurlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^PublishView/', views.PublishView.as_view()), url(r'^PublishDetailView/(?P<pk>\d+)', views.PublishDetailView.as_view()),]# 视图:from django.shortcuts import renderfrom rest_framework.views import APIViewfrom app01 import modelsfrom app01.MySer import BookSer,PublishSer,AuthorSerfrom rest_framework.response import Response# Create your views here.# 基本视图class PublishView(APIView): def get(self,request): publish_list = models.Publish.objects.all() bs = PublishSer(publish_list, many=True) return Response(bs.data) def post(self, request): bs = PublishSer(data=request.data) if bs.is_valid(): bs.save() return Response(bs.data) else: return Response(bs.errors)class PublishDetailView(APIView): def get(self, request, pk): publish_obj = models.Publish.objects.filter(pk=pk).first() bs = PublishSer(publish_obj, many=False) return Response(bs.data) def put(self, request, pk): publish_obj = models.Publish.objects.filter(pk=pk).first() bs = PublishSer(data=request.data, instance=publish_obj) if bs.is_valid(): bs.save() return Response(bs.data) else: return Response(bs.data) def delete(self, request, pk): models.Publish.objects.filter(pk=pk).delete() return Response("")# MySer.pyfrom rest_framework import serializersfrom app01 import modelsclass BookSer(serializers.ModelSerializer): class Meta: model = models.Book fields = '__all__'class PublishSer(serializers.ModelSerializer): class Meta: model = models.Publish fields = '__all__'class AuthorSer(serializers.ModelSerializer): class Meta: model = models.Author fields = '__all__'

基于mixins来封装的视图

其它不变,更改视图:

# 基于mixins来封装的视图from rest_framework.mixins import CreateModelMixin,\ ListModelMixin,\ RetrieveModelMixin,\ DestroyModelMixin,\ UpdateModelMixinfrom rest_framework.generics import GenericAPIViewclass PublishView(CreateModelMixin, ListModelMixin, GenericAPIView): queryset = models.Publish.objects.all() serializer_class = PublishSer 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 PublishDetailView(RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin, GenericAPIView): queryset = models.Publish.objects.all() serializer_class = PublishSer 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)

可以看出视图类中还是有很多冗余代码

mixins封装再封装,第三种方法

# 第三种写法:from rest_framework.generics import CreateAPIView,\ ListCreateAPIView,\ DestroyAPIView,\ RetrieveUpdateDestroyAPIViewclass PublishView(ListCreateAPIView): queryset = models.Publish.objects.all() serializer_class = PublishSerclass PublishDetailView(RetrieveUpdateDestroyAPIView): queryset = models.Publish.objects.all() serializer_class = PublishSer

还是有冗余代码

第四种写法,再次封装,全部写在一个类中

# 路由from django.conf.urls import urlfrom django.contrib import adminfrom app01 import viewsurlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^publish/$', views.PublishView.as_view({'get': 'list', 'post': 'create'})), url(r'^publish/(?P<pk>\d+)$', views.PublishView.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),]# 第四种写法:5个接口写在一个类中from rest_framework.viewsets import ModelViewSetclass PublishView(ModelViewSet): queryset = models.Publish.objects.all() serializer_class = PublishSer

补充:

from rest_framework.viewsets import ViewSetMixinfrom rest_framework.views import APIView# ViewSetMixin 重写了as_view方法class Test(ViewSetMixin,APIView): def aaa(self,request): return Response()

以上这篇Django框架之DRF 基于mixins来封装的视图详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章