django-rest-framework視圖和url

django-rest-framework視圖

GenericView

class GenericView(GenericAPIView):
    queryset = models.Role.objects.all()
    serializer_class = serializers.RoleSerializer
    pagination_class = PageNumberPagination

    def get(self, request):
        # 獲取數據
        data = self.get_queryset()
        # 獲取分頁數據
        page_data = self.paginate_queryset(data)
        # 獲取序列化數據
        resp = self.get_serializer(instance=page_data, many=True)
        return Response(resp.data)
  • GenericView在原來的ApiView上作了一點封裝,主要使用的有三個方法
    • get_queryset : 獲取查詢的queryset對象
    • paginate_queryset: 獲取分頁後的對象,須要接受一個queryset對象參數
    • get_serializer: 序列化數據,制定序列化對象和制定many的參數

GenericViewSet

class GenericView(GenericViewSet):

    def list(self, request):
        return Response('list')
from django.conf.urls import re_path

from . import views

urlpatterns = [
    re_path(r'^index/', views.GenericView.as_view({'get': 'list'})),
]
  • GenericViewSet的使用跟GenericView大體無差異,只是對應請求方法的函數須要自定義
    • url的as_view方法須要傳遞一個字典參數,字典的key就是對應的請求方法,value就是對應請求方法的處理函數

ModelViewSet

class GenericView(ModelViewSet):
    queryset = models.Role.objects.all()
    serializer_class = serializers.RoleSerializer
    pagination_class = PageNumberPagination
  • ModelViewSet就更高級了,它默認實現了增刪該查的方法,只須要配置好對應的屬性就能夠了

urlpython

from django.conf.urls import re_path

from . import views

urlpatterns = [
    re_path(r'^index/', views.GenericView.as_view({'get': 'list', 'post': 'update'})),
]

全自動生成路由django

from django.urls import path, include, re_path
from rest_framework import routers

from . import views

route = routers.DefaultRouter()

route.register('index', views.GenericView)

urlpatterns = [
    re_path('', include(route.urls))
]
相關文章
相關標籤/搜索