Django drf 视图

原来

class Page1View(View):
  pass

现在

class Page1View(APIView)
  pass

GenericAPIView(和APIView)差不多

from rest_framework.generics import GenericAPIView

class View1View(GenericAPIView):
    queryset = models.Role.objects.all()
    serializer_class = PagerSerializers
    pagination_class = MyPageNumberPagination
    def get(self, request, *args, **kwargs):
        # 获取数据
        roles = self.get_queryset()

        # [1, 1000] [1,10]
        pager_roles = self.paginate_queryset(roles)

        # 序列化
        ser = self.get_serializer(instance=pager_roles, many=True)

        return Response(ser.data)

GenericViewSet(路由系统有所变化)

re_path(r'^(?P[v1|v2]+)/v1/', views.View1View.as_view({'get': 'get'})),
from rest_framework.viewsets import GenericViewSet

class View1View(GenericViewSet):

    queryset = models.Role.objects.all()
    serializer_class = PagerSerializers
    pagination_class = MyPageNumberPagination
    def get(self, request, *args, **kwargs):
        # 获取数据
        roles = self.get_queryset()

        # [1, 1000] [1,10]
        pager_roles = self.paginate_queryset(roles)

        # 序列化
        ser = self.get_serializer(instance=pager_roles, many=True)

        return Response(ser.data)

ModelViewSet(路由系统有所变化)

该类内部已经完善了简单的增删改查路由

re_path(r'^(?P[v1|v2]+)/v1/(?P\d+)/$', views.View1View.as_view({'get': 'retrieve',
                                                                             'delete': 'destroy',
                                                                             'patch': 'perform_update',
                                                                             'update': 'update'})),
from rest_framework.viewsets import ModelViewSet

class View1View(ModelViewSet):
    queryset = models.Role.objects.all()
    serializer_class = PagerSerializers
    pagination_class = MyPageNumberPagination

  1. 简单的增删改查 ModelViewSet
  2. 增删 (CreateModelMixin, DestroyModelMixin) + GenericViewSet
  3. 复杂逻辑 GenericViewSet 或 APIView

你可能感兴趣的:(Django drf 视图)