视图集

发布时间 2024-01-09 22:10:05作者: 朱饱饱

视图集:

#视图集

# ViewSetMixin:重写了as_view

# ViewSet: 继承ViewSetMixin和APIView
# GenericViewSet:继承ViewSetMixin, generics.GenericAPIView

# ModelViewSet:继承mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,mixins.ListModelMixin,GenericViewSet
# ReadOnlyModelViewSet:继承mixins.RetrieveModelMixin,mixins.ListModelMixin,GenericViewSet

 

 

action的使用:

# 只要继承了ViewSetMixin类
# 路由配置:path('books_mix/', views.BookView.as_view({'get':'lqz'}))
# 视图类的方法中就会有个action
class BookView(ViewSet):
    def lqz(self,request,*args,**kwargs):
        print(self.action)
        return Response('lqz')
    
    
# ViewSetMixin以后只要继承它,路由的配置就发生变化了,只需要写映射即可








# action
    -当自动生成路由的时候,由于视图类中还有其它方法,是无法自动生成路由的
    -加action装饰器:
        -methods:什么请求方式会触发被装饰函数的执行
        -detail:是True是基于带id的路由生成的,如果是False,是基于不带id的路由生成的
        -@action(methods=['get'], detail=True)

 

 

路由的使用:

# 自动生成路由
# SimpleRouter
# DefaultRouter

# 继承了ViewSetMixin的视图类,以后写路由,可以自动生成
from rest_framework import routers
# 实例化得到一个对象
router = routers.SimpleRouter()
# 注册进路由
router.register('books', views.BookSetView)
# 把自动生成的路由配置到urlpatterns中
    -urlpatterns += router.urls
    -re_path(r'v1/', include(router.urls))
    
    
    
    
# 配置路由的方式
    -最原始的
        -path('books/', views.BookAPIView.as_view()),
    -ViewSetMixin的视图类
        -path('books_set/', views.BookSetView.as_view({'get':'list','post':'create'}))
    -ViewSetMixin的视图类
        -自动生成,上面讲的
        
        
        
        
 # action
    -当自动生成路由的时候,由于视图类中还有其它方法,是无法自动生成路由的
    -加action装饰器:
        -methods:什么请求方式会触发被装饰函数的执行
        -detail:是True是基于带id的路由生成的,如果是False,是基于不带id的路由生成的
        -@action(methods=['get'], detail=True)