自动生产路由
# ReadOnlyModelViewSet:两个接口,list和retrieve
from rest_framework.viewsets import ReadOnlyModelViewSet
class BookLIstretrieveView(ReadOnlyModelViewSet):
queryset = Book.objects.all()
serializer_class = Bookserializers
# ViewSetMixin:魔法,不能单独使用,必须配合视图类用,路由写法变了
from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action
class BookViewSet(ViewSet): # ViewSetMixin, views.APIView
queryset = Book.objects.all()
serializer_class = Bookserializers
''''
- 1 写在视图类方法上
class SendView(ViewSet):
# methods指定请求方法,可以传多个
# detail:只能传True和False
-False,不带id的路径:send/send_sms/
-True,带id的路径:send/2/send_sms/
#url_path:生成send后路径的名字,默认以方法名命名
# url_name:别名,反向解析使用,了解即可
@action(methods=['POST'], detail=False)
def send_sms(self, request):
'''
# @action(methods=['get'], detail=False) # http://127.0.0.1:8000/lyx/lyx/
@action(methods=['get'], detail=True) # http://127.0.0.1:8000/lyx/lyx/
def lyx(self, request, *args, **kwargs): # http://127.0.0.1:8000/lyx/1/lyx/
print(kwargs.get('pk'))
return Response("你好")
from django.urls import path, include
from index.views import *
from rest_framework import routers
'''
SimpleRouter
DefaultRouter===>多生产一个跟路由
'''
router = routers.SimpleRouter() # 创建一个 SimpleRouter 实例
router.register("book", BookLIstretrieveView) # 注册视图集
router.register("lyx", BookViewSet) # 注册视图集
'''
prefix 该视图集的路由前缀
viewset 视图集
base_name 路由别名的前缀
'''
urlpatterns = [
添加路由
# 方式2
path("", include(router.urls))
]
# 添加路由
# 方式一
# urlpatterns += router.urls
# http://127.0.0.1:8000/book/
# http://127.0.0.1:8000/book/<int:pk>/