Django視圖擴(kuò)展類知識(shí)點(diǎn)詳解
擴(kuò)展類必須配合GenericAPIView使用擴(kuò)展類內(nèi)部的方法,在調(diào)用序列化器時(shí),都是使用get_serializer
需要自定義get、post等請(qǐng)求方法,內(nèi)部實(shí)現(xiàn)調(diào)用擴(kuò)展類對(duì)應(yīng)方法即可 。
一、mixins的視圖子類
作用:
提供了幾種后端視圖(對(duì)數(shù)據(jù)資源進(jìn)行曾刪改查)處理流程的實(shí)現(xiàn),如果需要編寫的視圖屬于這五種,則視圖可以通過繼承相應(yīng)的擴(kuò)展類來復(fù)用代碼,減少自己編寫的代碼量 。
這五個(gè)擴(kuò)展類需要搭配GenericAPIView父類,因?yàn)槲鍌€(gè)擴(kuò)展類的實(shí)現(xiàn)需要調(diào)用GenericAPIView提供的序列化器與數(shù)據(jù)庫查詢的方法。
1.1 ListModelMixin
列表視圖擴(kuò)展類,提供list(request, *args, **kwargs)方法快速實(shí)現(xiàn)列表視圖,返回200狀態(tài)碼。
- 提供list方法,快速實(shí)現(xiàn)列表視圖
- 調(diào)用GenericAPIView設(shè)置好的結(jié)果集
- 調(diào)用GenericAPIView設(shè)置好的序列化器
該Mixin的list()方法會(huì)對(duì)數(shù)據(jù)進(jìn)行過濾和分頁。
源代碼:
from rest_framework.mixins import ListModelMixin
class ListModelMixin(object):
"""
List a queryset.
"""
def list(self, request, *args, **kwargs):
# 過濾
queryset = self.filter_queryset(self.get_queryset())
# 分頁
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
# 序列化
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
舉例:
from rest_framework.mixins import ListModelMixin
from rest_framework.generics import GenericAPIView
class BookListView(ListModelMixin, GenericAPIView):
queryset = BookInfo.objects.all()
serializer_class = BookInfoSerializer
def get(self, request):
return self.list(request)
1.2 CreateModelMixin
創(chuàng)建視圖擴(kuò)展類,提供create(request, *args, **kwargs)方法快速實(shí)現(xiàn)創(chuàng)建資源的視圖,成功返回201狀態(tài)碼。
- 提供create(request, *args, **kwargs)方法快速實(shí)現(xiàn)創(chuàng)建資源的視圖
- 實(shí)際創(chuàng)建功能由序列化的save方法完成
- save方法會(huì)去調(diào)用序列化器的create方法
如果序列化器對(duì)前端發(fā)送的數(shù)據(jù)驗(yàn)證失敗,返回400錯(cuò)誤。
源代碼:
from rest_framework.mixins import CreateModelMixin
class CreateModelMixin(object):
"""
Create a model instance.
"""
def create(self, request, *args, **kwargs):
# 獲取序列化器
serializer = self.get_serializer(data=request.data)
# 驗(yàn)證
serializer.is_valid(raise_exception=True)
# 保存
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def perform_create(self, serializer):
serializer.save()
def get_success_headers(self, data):
try:
return {'Location': str(data[api_settings.URL_FIELD_NAME])}
except (TypeError, KeyError):
return {}
1.3 RetrieveModelMixin
詳情視圖擴(kuò)展類,提供retrieve(request, *args, **kwargs)方法,可以快速實(shí)現(xiàn)返回一個(gè)存在的數(shù)據(jù)對(duì)象。
如果存在,返回200, 否則返回404。
源代碼:
from rest_framework.mixins import RetrieveModelMixin
class RetrieveModelMixin(object):
"""
Retrieve a model instance.
"""
def retrieve(self, request, *args, **kwargs):
# 獲取對(duì)象,會(huì)檢查對(duì)象的權(quán)限
instance = self.get_object()
# 序列化
serializer = self.get_serializer(instance)
return Response(serializer.data)
舉例:
from rest_framework.mixins import RetrieveModelMixin
from rest_framework.generics import GenericAPIView
class BookDetailView(RetrieveModelMixin, GenericAPIView):
queryset = BookInfo.objects.all()
serializer_class = BookInfoSerializer
def get(self, request, pk):
return self.retrieve(request)
1.4 UpdateModelMixin
更新視圖擴(kuò)展類,提供update(request, *args, **kwargs)方法
- 可以快速實(shí)現(xiàn)更新一個(gè)存在的數(shù)據(jù)對(duì)象。
- 同時(shí)也提供partial_update(request, *args, **kwargs)方法,可以實(shí)現(xiàn)局部更新。
- 內(nèi)部更新功能調(diào)用序列化器的save方法
- save方法會(huì)調(diào)用序列化器的update方法
成功返回200,序列化器校驗(yàn)數(shù)據(jù)失敗時(shí),返回400錯(cuò)誤。
源代碼:
from rest_framework.mixins import UpdateModelMixin
class UpdateModelMixin(object):
"""
Update a model instance.
"""
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
if getattr(instance, '_prefetched_objects_cache', None):
# If 'prefetch_related' has been applied to a queryset, we need to
# forcibly invalidate the prefetch cache on the instance.
instance._prefetched_objects_cache = {}
return Response(serializer.data)
def perform_update(self, serializer):
serializer.save()
def partial_update(self, request, *args, **kwargs):
kwargs['partial'] = True
return self.update(request, *args, **kwargs)
1.5 DestroyModelMixin
刪除視圖擴(kuò)展類,提供destroy(request, *args, **kwargs)方法,可以快速實(shí)現(xiàn)刪除一個(gè)存在的數(shù)據(jù)對(duì)象。
成功返回204,不存在返回404。
源代碼:
from rest_framework.mixins import DestroyModelMixin
class DestroyModelMixin(object):
"""
Destroy a model instance.
"""
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
self.perform_destroy(instance)
return Response(status=status.HTTP_204_NO_CONTENT)
def perform_destroy(self, instance):
instance.delete()
使用GenericAPIView和視圖擴(kuò)展類,實(shí)現(xiàn)api接口,代碼:
"""GenericAPIView結(jié)合視圖擴(kuò)展類實(shí)現(xiàn)api接口"""
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin,CreateModelMixin
class Students2GenericAPIView(GenericAPIView,ListModelMixin,CreateModelMixin):
# 本次視圖類中要操作的數(shù)據(jù)[必填]
queryset = Student.objects.all()
# 本次視圖類中要調(diào)用的默認(rèn)序列化器[玄天]
serializer_class = StudentModelSerializer
def get(self, request):
"""獲取多個(gè)學(xué)生信息"""
return self.list(request)
def post(self,request):
"""添加學(xué)生信息"""
return self.create(request)
from rest_framework.mixins import RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin
from rest_framework.generics import GenericAPIView
class Student2GenericAPIView(GenericAPIView,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin):
queryset = Student.objects.all()
serializer_class = StudentModelSerializer
# 在使用GenericAPIView視圖獲取或操作單個(gè)數(shù)據(jù)時(shí),視圖方法中的代表主鍵的參數(shù)最好是pk
def get(self,request,pk):
"""獲取一條數(shù)據(jù)"""
return self.retrieve(request,pk)
def put(self,request,pk):
"""更新一條數(shù)據(jù)"""
return self.update(request,pk)
def delete(self,request,pk):
"""刪除一條數(shù)據(jù)"""
return self.destroy(request,pk)
二 、Generic的視圖子類
2.1 CreateAPIView
提供 post方法
繼承自: GenericAPIView、`CreateModelMixin
2.2 ListAPIView
提供 get 方法
繼承自:GenericAPIView、ListModelMixin
2.3 RetrieveAPIView
提供 get方法
繼承自: GenericAPIView、RetrieveModelMixin
2.4 DestoryAPIView
提供 delete方法
繼承自:GenericAPIView、DestoryModelMixin
2.5 UpdateAPIView
提供 put和 patch方法
繼承自:GenericAPIView、UpdateModelMixin
2.6 RetrieveUpdateAPIView
提供 get、put、patch方法
繼承自: GenericAPIView、RetrieveModelMixin、UpdateModelMixin
2.7 RetrieveUpdateDestoryAPIView
提供 get、put、patch、delete方法
繼承自:GenericAPIView、RetrieveModelMixin、UpdateModelMixin、DestoryModelMixin
以上就是本次介紹的全部知識(shí)點(diǎn)內(nèi)容,感謝大家的學(xué)習(xí)和對(duì)腳本之家的支持。
相關(guān)文章
Python實(shí)現(xiàn)按照指定要求逆序輸出一個(gè)數(shù)字的方法
這篇文章主要介紹了Python實(shí)現(xiàn)按照指定要求逆序輸出一個(gè)數(shù)字的方法,涉及Python針對(duì)字符串的遍歷、判斷、輸出等相關(guān)操作技巧,需要的朋友可以參考下2018-04-04
python模擬實(shí)現(xiàn)斗地主發(fā)牌
這篇文章主要為大家詳細(xì)介紹了python代碼模擬實(shí)現(xiàn)斗地主發(fā)牌,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-01-01
解決Python數(shù)據(jù)可視化中文部分顯示方塊問題
這篇文章主要介紹了解決Python數(shù)據(jù)可視化中文部分顯示方塊問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05
Python實(shí)現(xiàn)的調(diào)用C語言函數(shù)功能簡單實(shí)例
這篇文章主要介紹了Python實(shí)現(xiàn)的調(diào)用C語言函數(shù)功能,結(jié)合簡單實(shí)例形式分析了Python使用ctypes模塊調(diào)用C語言函數(shù)的具體步驟與相關(guān)操作技巧,需要的朋友可以參考下2019-03-03
Python3 pip3 list 出現(xiàn) DEPRECATION 警告的解決方法
今天小編就為大家分享一篇Python3 pip3 list 出現(xiàn) DEPRECATION 警告的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-02-02
Python學(xué)習(xí)之不同數(shù)據(jù)類型間的轉(zhuǎn)換總結(jié)
類型轉(zhuǎn)換,就是將自身的數(shù)據(jù)類型變成新的數(shù)據(jù)類型,并擁有新的數(shù)據(jù)類型的所有功能的過程。本文將詳細(xì)為大家介紹如何在Python中實(shí)現(xiàn)不同數(shù)據(jù)類型的轉(zhuǎn)換,感興趣的可以了解一下2022-03-03

