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)
get_queryset
: 獲取查詢的queryset對象paginate_queryset
: 獲取分頁後的對象,須要接受一個queryset對象參數get_serializer
: 序列化數據,制定序列化對象和制定many的參數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'})), ]
class GenericView(ModelViewSet): queryset = models.Role.objects.all() serializer_class = serializers.RoleSerializer pagination_class = PageNumberPagination
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)) ]