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.pswp.cn/news/280436.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/280436.shtml
英文地址,請注明出處:http://en.pswp.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;向其添加…