views.py:
from rest_framework.viewsets import GenericViewSet from rest_framework import serializers from rest_framework.pagination import PageNumberPagination from drf import models from rest_framework.response import Response class PagerSerializer(serializers.ModelSerializer): class Meta: model = models.Role fields = "__all__" class TestView(GenericViewSet): # 看源码 queryset = models.Role.objects.all() # 数据 serializer_class = PagerSerializer # 序列化 pagination_class = PageNumberPagination # 分页 def list(self, request, *args, **kwargs): # 获取数据 roles = self.get_queryset() # 分页 role_page = self.paginate_queryset(roles) # 序列化 ser = self.get_serializer(instance=role_page, many=True) return Response(ser.data)
urls.py:
from django.urls import re_path, include from drf import views from rest_framework import routers from django.conf.urls import url router = routers.DefaultRouter() router.register("aaaaa", views.TestView) router.register("bbbbb", views.TestView) urlpatterns = [ re_path('view/$', views.TestView.as_view({"get": "list"})), url(r'^', include(router.urls)), # 这里需要用 url ]
最先的视图需要用 re_path 匹配,不能用 path
访问一个不存在的路径
都加了前缀