Django框架五個擴展類的使用方法

1)ListModelMixin
列表視圖擴展類,提供list(request, *args, **kwargs)方法快速實現列表視圖,返回200狀態碼。

該Mixin的list方法會對數據進行過濾和分頁。

from rest_framework import mixins
class BookListView(mixins.ListModelMixin,GenericAPIView):
    """
    GenericAPIView實現獲取所有圖書信息的接口"""
    serializer_class = BookInfoSerializer
    # 指定查詢集  queryset負責接受查詢集
    queryset = BookInfo.objects.all()
    def get(self,request):
        return self.list(request)

2)CreateModelMixin
創建視圖擴展類,提供create(request, *args, **kwargs)方法快速實現創建資源的視圖,成功返回201狀態碼。

如果序列化器對前端發送的數據驗證失敗,返回400錯誤。

# 子類視圖ListAPIView
class BookListView(ListAPIView):
    """
    ListAPIView實現獲取所有圖書信息的接口
    ListAPIView 自己寫了 def get()..... ret...
    所以我們不用在寫
    """
    # 指定反序列化器類
    serializer_class = BookInfoSerializer
    # 指定查詢集  queryset負責接受查詢集
    queryset = BookInfo.objects.all()

3) RetrieveModelMixin

詳情視圖擴展類,提供retrieve(request, *args, **kwargs)方法,可以快速實現返回一個存在的數據對象。

如果存在,返回200, 否則返回404。

class BookDetailView(mixins.RetrieveModelMixin,GenericAPIView):
    """GenericAPIView查詢單一的數據的接口"""
 
    # 指定反序列化器類
    serializer_class = BookInfoSerializer
    # 指定查詢集  queryset負責接受查詢集
    queryset = BookInfo.objects.all()
    def get(self,request,pk):
        return self.retrieve(request)

4)UpdateModelMixin
更新視圖擴展類,提供update(request, *args, **kwargs)方法,可以快速實現更新一個存在的數據對象。

同時也提供partial_update(request, *args, **kwargs)方法,可以實現局部更新。

成功返回200,序列化器校驗數據失敗時,返回400錯誤。

class BookUpdateView(mixins.UpdateModelMixin,GenericAPIView):
    """UpdateModelMixin獲取數據"""
    # 指定反序列化器類
    serializer_class = BookInfoSerializer
    # 指定查詢集  queryset負責接收查詢集
    queryset = BookInfo.objects.all()
 
    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

5)DestroyModelMixin
刪除視圖擴展類,提供destroy(request, *args, **kwargs)方法,可以快速實現刪除一個存在的數據對象。

成功返回204,不存在返回404。

class BookDestroyView(mixins.DestroyModelMixin,GenericAPIView):
    """UpdateModelMixin獲取數據"""
    # 指定反序列化器類
    serializer_class = BookInfoSerializer
    # 指定查詢集  queryset負責接收查詢集
    queryset = BookInfo.objects.all()
    
    def delete(self,request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

幾個可用子類視圖
1) CreateAPIView
提供 post 方法

繼承自: GenericAPIView、CreateModelMixin

2)ListAPIView
提供 get 方法

繼承自:GenericAPIView、ListModelMixin

3)RetrieveAPIView
提供 get 方法

繼承自: GenericAPIView、RetrieveModelMixin

4)DestoryAPIView
提供 delete 方法

繼承自:GenericAPIView、DestoryModelMixin

5)UpdateAPIView
提供 put 和 patch 方法

繼承自:GenericAPIView、UpdateModelMixin

6)RetrieveUpdateAPIView
提供 get、put、patch方法

繼承自: GenericAPIView、RetrieveModelMixin、UpdateModelMixin

7)RetrieveUpdateDestoryAPIView
提供 get、put、patch、delete方法

繼承自:GenericAPIView、RetrieveModelMixin、UpdateModelMixin、DestoryModelMixin

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章