Django REST framwork-06-使用 ViewSets 视图集和 Routers 路由

Django REST framwork-06-使用 ViewSets 视图集和 Routers 路由_第1张图片

文章目录

  • `GenericViewSet`
    • 定义视图
    • 注册路由
    • 访问
  • `ReadOnlyModelViewSet`
    • 源码
  • `ModelViewSet`
    • 源码
      • `ModelViewSet` 源码
      • `GenericViewSet` 源码

GenericViewSet

重写了 .as_view 方法,和 DRF 的 Routers 结合,可以简化路由配置。

返回一组列表数据

定义视图

from rest_framework import viewsets
from rest_framework import mixins


class ServerViewSet(
    mixins.ListModelMixin,viewsets.GenericViewSet):
    '''Viewsets.GenericViewSet 实现服务器列表'''
    queryset = Server.objects.all()
    serializer_class = ServerSerializer

注册路由

api/urls.py

from django.urls import path, include, re_path

from . import views

from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'servers-router', views.ServerViewSet)

urlpatterns = [
        path('', include(router.urls)),
]

访问

http://127.0.0.1/api/server-router

ReadOnlyModelViewSet

查一组列表数据和具体一个对象的详情数据(字典类型)

对象详情数据,是通过路由传递主键 id 的值,之后利用 DRFRouters 注册的方式,不需要再添加额外的路由。
就是说列表数据和详情数据,只要注册一次路由即可。

from rest_framework.viewsets import  ReadOnlyModelViewSet

源码

class ReadOnlyModelViewSet(mixins.RetrieveModelMixin,
                           mixins.ListModelMixin,
                           GenericViewSet):
    """
    A viewset that provides default `list()` and `retrieve()` actions.
    """
    pass

ModelViewSet

集成如下功能:

  1. 增删改
  2. 查一组数据
  3. 查单个数据

源码

ModelViewSet 源码

class ModelViewSet(mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.UpdateModelMixin,
                   mixins.DestroyModelMixin,
                   mixins.ListModelMixin,
                   GenericViewSet):
    """
    A viewset that provides default `create()`, `retrieve()`, `update()`,
    `partial_update()`, `destroy()` and `list()` actions.
    """
    pass

GenericViewSet 源码

class GenericViewSet(ViewSetMixin, generics.GenericAPIView):
    """
    The GenericViewSet class does not provide any actions by default,
    but does include the base set of generic view behavior, such as
    the `get_object` and `get_queryset` methods.
    """
    pass

你可能感兴趣的:(Django,REST,framwork,django,python,后端)