Django視圖擴展類知識點詳解
擴展類必須配合GenericAPIView使用擴展類內(nèi)部的方法,在調(diào)用序列化器時,都是使用get_serializer
需要自定義get、post等請求方法,內(nèi)部實現(xiàn)調(diào)用擴展類對應(yīng)方法即可 。
一、mixins的視圖子類
作用:
提供了幾種后端視圖(對數(shù)據(jù)資源進行曾刪改查)處理流程的實現(xiàn),如果需要編寫的視圖屬于這五種,則視圖可以通過繼承相應(yīng)的擴展類來復(fù)用代碼,減少自己編寫的代碼量 。
這五個擴展類需要搭配GenericAPIView父類,因為五個擴展類的實現(xiàn)需要調(diào)用GenericAPIView提供的序列化器與數(shù)據(jù)庫查詢的方法。
1.1 ListModelMixin
列表視圖擴展類,提供list(request, *args, **kwargs)方法快速實現(xiàn)列表視圖,返回200狀態(tài)碼。
- 提供list方法,快速實現(xiàn)列表視圖
- 調(diào)用GenericAPIView設(shè)置好的結(jié)果集
- 調(diào)用GenericAPIView設(shè)置好的序列化器
該Mixin的list()方法會對數(shù)據(jù)進行過濾和分頁。
源代碼:
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)建視圖擴展類,提供create(request, *args, **kwargs)方法快速實現(xiàn)創(chuàng)建資源的視圖,成功返回201狀態(tài)碼。
- 提供create(request, *args, **kwargs)方法快速實現(xiàn)創(chuàng)建資源的視圖
- 實際創(chuàng)建功能由序列化的save方法完成
- save方法會去調(diào)用序列化器的create方法
如果序列化器對前端發(fā)送的數(shù)據(jù)驗證失敗,返回400錯誤。
源代碼:
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)
# 驗證
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
詳情視圖擴展類,提供retrieve(request, *args, **kwargs)方法,可以快速實現(xiàn)返回一個存在的數(shù)據(jù)對象。
如果存在,返回200, 否則返回404。
源代碼:
from rest_framework.mixins import RetrieveModelMixin
class RetrieveModelMixin(object):
"""
Retrieve a model instance.
"""
def retrieve(self, request, *args, **kwargs):
# 獲取對象,會檢查對象的權(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
更新視圖擴展類,提供update(request, *args, **kwargs)方法
- 可以快速實現(xiàn)更新一個存在的數(shù)據(jù)對象。
- 同時也提供partial_update(request, *args, **kwargs)方法,可以實現(xiàn)局部更新。
- 內(nèi)部更新功能調(diào)用序列化器的save方法
- save方法會調(diào)用序列化器的update方法
成功返回200,序列化器校驗數(shù)據(jù)失敗時,返回400錯誤。
源代碼:
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
刪除視圖擴展類,提供destroy(request, *args, **kwargs)方法,可以快速實現(xiàn)刪除一個存在的數(shù)據(jù)對象。
成功返回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和視圖擴展類,實現(xiàn)api接口,代碼:
"""GenericAPIView結(jié)合視圖擴展類實現(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)用的默認序列化器[玄天]
serializer_class = StudentModelSerializer
def get(self, request):
"""獲取多個學生信息"""
return self.list(request)
def post(self,request):
"""添加學生信息"""
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視圖獲取或操作單個數(shù)據(jù)時,視圖方法中的代表主鍵的參數(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
以上就是本次介紹的全部知識點內(nèi)容,感謝大家的學習和對腳本之家的支持。
相關(guān)文章
pytorch常用函數(shù)之torch.randn()解讀
這篇文章主要介紹了pytorch常用函數(shù)之torch.randn()解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
pycharm上的python虛擬環(huán)境移到離線機器上的方法步驟
本人在工作中需要在離線Windows環(huán)境中使用,本文主要介紹了pycharm上的python虛擬環(huán)境移到離線機器上的方法步驟,具有一定的參考價值,感興趣的可以了解一下2021-10-10
Python中XML轉(zhuǎn)JSON、XML轉(zhuǎn)字典代碼示例
大家都知道python的字典和json類似,那么可不可以先將xml轉(zhuǎn)換成json再去做其他的事情呢,下面這篇文章主要給大家介紹了關(guān)于Python中XML轉(zhuǎn)JSON、XML轉(zhuǎn)字典的相關(guān)資料,需要的朋友可以參考下2024-02-02
開源軟件包和環(huán)境管理系統(tǒng)Anaconda的安裝使用
Anaconda是一個用于科學計算的Python發(fā)行版,支持 Linux, Mac, Windows系統(tǒng),提供了包管理與環(huán)境管理的功能,可以很方便地解決多版本python并存、切換以及各種第三方包安裝問題。2017-09-09
python+appium自動化測試之如何控制App的啟動和退出
本文主要介紹了python+appium自動化測試之如何控制App的啟動和退出,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02

