rest_framework05:GenericAPIView用法/扩展类5个/子类9个/ViewSetMixin 自定义方法名字

GenericAPIView

1.视图层类使用GenericAPIView继承,能简化类里的方法code。

2.简化后的方法code格式基本通用,简单修改即可应用到其他类。

一、class开始加入

    queryset = Book.objectsserializer_class = BookModelSerializer

二、方法里获取对象

a.查询一个使用,如需要pk值查询

book = self.get_object()

b.查询多个,如获取所有对象

 book = self.get_queryset()

c.序列化方法使用self.get_serializer()

括号内原来是什么参数,就写什么参数,如

instance=book, data=request.data,

many=True

三、代码views.py

from app01.models import Book
from app01.ser import BookSerializer,BookModelSerializer
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
# 自己学的response
from app01.utils import MyResponse# 基于GenericAPIView
class BookView(GenericAPIView):queryset = Book.objectsserializer_class = BookModelSerializerdef get(self, request, pk):book = self.get_object()book_ser = self.get_serializer(book)return Response(book_ser.data)def put(self, request, pk):response = MyResponse()book = self.get_object()book_ser = self.get_serializer(instance=book, data=request.data)# 要数据验证if book_ser.is_valid():  # 返回True 表示验证通过book_ser.save()response.data = book_ser.dataelse:response.status= 101response.msg = '数据校验失败'response.data= book_ser.errorsreturn Response(response.get_dic)def delete(self, request, pk):ret = Book.objects.filter(pk=pk).delete()return Response({'status': 100, 'msg': '删除成功'})class BooksView(GenericAPIView):queryset = Book.objectsserializer_class = BookModelSerializer# 使用封装responsedef get(self, request):response=MyResponse()book = self.get_queryset()book_ser = self.get_serializer(book, many=True)  # 序列化多条。 如果一条,不需要写response.data = book_ser.datareturn Response(response.get_dic)# 新增def post(self, request):response=MyResponse()# 新增没有instance,只有databook_ser = self.get_serializer(data=request.data)# 如果没有data=,会报错。第一个参数是instance# book_ser = BookSerializer(request.data)# 校验字段if book_ser.is_valid():book_ser.save()response.data = book_ser.dataelse:response.status = 102response.msg = '新增数据校验失败'response.data = book_ser.datareturn Response(response.get_dic)

5个视图扩展类

分别如下,

ListModelMixin,CreateModelMixin,UpdateModelMixin,DestroyModelMixin,RetrieveModelMixin
from app01.models import Book
from rest_framework.mixins import ListModelMixin,CreateModelMixin,UpdateModelMixin,DestroyModelMixin,RetrieveModelMixin# 5个扩展类
class Books3View(GenericAPIView,ListModelMixin,CreateModelMixin):queryset = Book.objectsserializer_class = BookModelSerializerdef get(self,request):return self.list(request)def post(self,request):return self.create(request)class Book3DetailView(GenericAPIView,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin):queryset = Book.objectsserializer_class = BookModelSerializerdef get(self,request,pk):return self.retrieve(request,pk)def put(self,request,pk):return self.update(request,pk)def delete(self,request,pk):return self.destroy(request,pk)

GenericAPIView的视图子类 9个

create,update等对应方法可以单独继承,也有组合的类继承,所以有9个。

# 基于 GenericAPIView的视图子类9个
from rest_framework.generics import CreateAPIView,ListAPIView,UpdateAPIView,RetrieveAPIView,DestroyAPIView,ListCreateAPIView,RetrieveUpdateAPIView,RetrieveDestroyAPIView,RetrieveUpdateDestroyAPIView# class Books4View(ListAPIView,CreateAPIView):
class Books4View(ListCreateAPIView):queryset = Book.objectsserializer_class = BookModelSerializer# class Book4DetailView(UpdateAPIView,RetrieveAPIView,DestroyAPIView):
class Book4DetailView(RetrieveUpdateDestroyAPIView):queryset = Book.objectsserializer_class = BookModelSerializer

ModelViewSet

简写成一个class,路由需要特别写法。

urls.py

  path('books5/', views.Books5View.as_view(actions={'get':'list','post':'create'})),re_path('^books5/(?P<pk>\d+)', views.Books5View.as_view(actions={'get':'retrieve','put':'update','delete':'destroy'})),

views.py

# 使用ModelViewSet编写5个接口
from rest_framework.viewsets import ModelViewSet
class Books5View(ModelViewSet):queryset = Book.objectsserializer_class = BookModelSerializer

使用ViewSetMixin 自定义方法名字

path('books6/', views.Books6View.as_view(actions={'get': 'get_all_book'})),

# 使用ViewSetMixin 自定义方法名字
from rest_framework.viewsets import ViewSetMixin# ViewSetMixin一定放在前面,重写as_view方法
class Books6View(ViewSetMixin,GenericAPIView):def get_all_book(self,request):books = Book.objects.all()book_ser = BookSerializer(books, many=True)return Response(book_ser.data)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/280436.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

1.操作系统概述

2019独角兽企业重金招聘Python工程师标准>>> 操作系统的发展过程 无操作系统的计算机系统单道批处理系统&#xff08;50年代&#xff0c;系统资源利用率低&#xff09;多道批处理系统&#xff08;60年代&#xff09;分时系统&#xff08;70年代&#xff09;实时系统…

测听hl和nhl的区别_播放NHL曲棍球的最便宜方法(无电缆)

测听hl和nhl的区别If you’re like me, you watch hockey, and…basically no other sports. You also, like me, would like to skip the cable subscription. So what’s the cheapest way to watch NHL hockey online so you can cut the cord? 如果您像我一样&#xff0c;…

制作一个让客户满意的软件

我看了《构建之法》的第八章“需求分析”我对如何制作一个让客户满意的软件有了一点儿头绪&#xff0c;的但是还是有一些迷惑。我通过看书总结和百度查找有了一点儿总结&#xff1a;我们在制作软件的过程中应该及时与用户沟通交流&#xff0c;交换意见&#xff0c;并及时实现用…

rest_framework06:自动生成路由\action使用\认证

自动生成路由 # 1.导入routers模块 from rest_framework import routers# 2.实例化类 routerrouters.SimpleRouter()# 3.注册 # (前缀,继承自ModelViewSet视图类,别名) router.register(books7,views.BooksView) # 不要加斜杠# 4.加入 urlpatternsrouter.urls action使用 装…

char data[0]在struct末尾的用法

在实际的编程中&#xff0c;我们经常需要使用变长数组&#xff0c;但是C语言并不支持变长的数组。此时&#xff0c;我们可以使用结构体的方法实现C语言变长数组。 struct MyData { int nLen; char data[0];}; 在结构中&#xff0c;data是一个数组名&#xff1b;但该数组没有元素…

使用Java实现K-Means聚类算法

2019独角兽企业重金招聘Python工程师标准>>> 关于K-Means介绍很多&#xff0c;还不清楚可以查一些相关资料。 个人对其实现步骤简单总结为4步: 1.选出k值,随机出k个起始质心点。 2.分别计算每个点和k个起始质点之间的距离,就近归类。 3.最终中心点集可以划分为…

在PowerShell中显示高级进度条

如果你需要编写一些PowerShell脚本&#xff0c;尤其在处理一些相对复杂的任务时&#xff0c;你可能希望添加进度条的功能&#xff0c;以便随时可以了解进展情况。Write-Progress 这个命令可以帮助你完成简单的需求&#xff0c;请参考官方文档即可&#xff0c;但下图一个示例&am…

当检测到运动时如何自动打开门灯

If it’s dark out and someone comes to your door, you probably can’t see them unless your porch light is on. Furthermore, if a potential burglar approaches your front door, a motion light can help scare them away. 如果天黑了&#xff0c;有人进了您的门&…

分布式系统的那些事儿(六) - SOA架构体系

有十来天没发文了&#xff0c;实在抱歉&#xff01;最近忙着录视频&#xff0c;同时也做了个开源的后台管理系统LeeCX&#xff0c;目前比较简单&#xff0c;但是后续会把各类技术完善。具体可以点击“原文链接”。 那么今天继续说分布式系统的那些事。 我们现在动不动就讲分布式…

rest_framework07:权限/频率/过滤组件/排序/异常处理封装Response对象

权限 写一个类&#xff0c;继承BasePermission&#xff0c;如果通过返回True&#xff0c;否则False 这里需要配合认证使用&#xff0c;否则没有user_type属性。 from rest_framework.permissions import BasePermissionclass UserPermission(BasePermission):def has_permis…

在阿里,我们如何管理测试环境

为什么80%的码农都做不了架构师&#xff1f;>>> 作者&#xff1a;林帆&#xff08;花名金戟&#xff09;&#xff0c;阿里巴巴研发效能部技术专家 相关阅读&#xff1a;在阿里&#xff0c;我们如何管理代码分支 前言 阿里的许多实践看似简单&#xff0c;背后却蕴涵…

数据库_7_SQL基本操作——表操作

SQL基本操作——表操作 建表的过程就是声明列的过程。 表与字段是密不可分的。 一、新增数据表 create table [if not exists] 表名( 字段名字 数据类型, 字段名字 数据类型 -- 最后一行不需要逗号 )[表选项];if not exists:如果表名不存在&#xff0c;那么就创建&#xff0c;…

EXT.NET 更改lable和Text的颜色

2019独角兽企业重金招聘Python工程师标准>>> &#xfeff;&#xfeff; <ext:TextField ID"TextField1" " runat"server" FieldLabel"编号" LabelWidth"60" LabelAlign"Left" LabelStyle"color:red…

rest_framework08:分页器/根据ip进行频率限制

分页器 # 查询所有&#xff0c;才需要分页 from rest_framework.generics import ListAPIView# 内置三种分页方式 from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination,CursorPaginationPageNumberPaginationclass MyPageNumberPagination(Pag…

NYOJ746 整数划分

该题是一道区间DP的题目&#xff0c;做了几道区间DP&#xff0c;说起来高大上&#xff0c;也就是DP在区间内的形式而已&#xff0c;核心思想还是要想到转移->规划。 题意是在n位数中间加m个称号&#xff0c;使得最终乘积最大。 状态转移方程如下&#xff1a; dp[ i ][ j ]ma…

Spring MVC实现文件下载

方法一&#xff1a; RequestMapping("/testHttpMessageDown")public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {File file new File(request.getSession().getServletContext().getClassLoader().getResource("…

[MobX State Tree数据组件化开发][3]:选择正确的types.xxx

?系列文章目录? 定义Model时&#xff0c;需要正确地定义props中各字段的类型。本文将对MST提供的各种类型以及类型的工厂方法进行简单的介绍&#xff0c;方便同学们在定义props时挑选正确的类型。 前提 定义props之前&#xff0c;有一个前提是&#xff0c;你已经明确地知道这…

ubuntu系统备份和还原_如何使用Aptik在Ubuntu中备份和还原您的应用程序和PPA

ubuntu系统备份和还原If you need to reinstall Ubuntu or if you just want to install a new version from scratch, wouldn’t it be useful to have an easy way to reinstall all your apps and settings? You can easily accomplish this using a free tool called Apti…

rest_framework09:自动生成接口文档(简略)

coreapi 参考 python/Django-rest-framework框架/8-drf-自动生成接口文档 | Justin-刘清政的博客 Swagger 很多语言都支持&#xff0c;看起来用的人多。 参考fastapi的界面

AppDomainManager后门的实现思路

本文讲的是AppDomainManager后门的实现思路&#xff0c;0x00 前言从Casey SmithsubTee学到的一个技巧&#xff1a;针对.Net程序&#xff0c;通过修改AppDomainManager能够劫持.Net程序的启动过程。 如果劫持了系统常见.Net程序如powershell.exe的启动过程&#xff0c;向其添加…