路由Routers

路由Routers

对于视图集ViewSet,除了可以自己手动指明请求方式与动作action之间,还可以使用Routers来快速实现路由信息

rest framework提供了两个router

  • SimpleRouter
  • DefaultRouter
#1.在urls.py中配置
path('books/', views.BookView.as_view()),
re_path('book/(?P<pk>\d+)', views.BookDetailView.as_view()),

#2.一旦视图类,继承了ViewSetMixin,路由
  path('books5/', views.Book5View.as_view(actions={'get': 'list', 'post': 'create'})),
re_path('books5/(?P<pk>\d+)',views.Book5View.as_view(actions={'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),

#3.继承自视图类,ModelViewSet的路由写法(自动生成路由)

1、自动生成路由

# urls.py

# 第一步,导入routers模块
	from rest_framework import routers
# 第二部,有两个类,实例化得到对象
    # routers.DefaultRouter:生成的路由更多,
    # routers.SimpleRouter
	router = routers.SimpleRouter()
# 第三步,注册
    # router.register(prefix='前缀', viewset=继承自ModelViewSet视图类,basename='别名')
    router.register(prefix='books', viewset=views.BookViewSet)
# 第四步,自动生成路由
	# print(router.urls)
    urlpatterns += router.urls
#models.py
from django.db import models
class Book(models.Model):
    name = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=8, decimal_places=3)
    publish = models.CharField(max_length=32)

#ser.py
from rest_framework import serializers
from app01.models import Book
class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'
               
#views.py
from rest_framework.viewsets import ModelViewSet
from app01.models import Book
from app01.serializer import BookSerializer
class BookViewSet(ModelViewSet):
    queryset = Book.objects
    serializer_class = BookSerializer

2、action的使用

为了给继承自ModelsViewSet的视图类中自定义的函数也添加路由
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.decorators import action  # 装饰器
from app01.models import Book
from app01.serializer import BookSerializer

class BookViewSet(ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    # methods传一个列表,列表中放请求方式,
    # detail,布尔类型,
    #
    @action(methods=['get'], detail=False)
    # ^books/get_1/$ [name='book-get-1'] # 朝这个地址发送get请求,会执行下面的函数
    def get_1(self, request):
        book_obj = self.get_queryset()[:2]  # 从0开始截取一条
        ser = self.get_serializer(book_obj, many=True)
        return Response(ser.data)

    @action(methods=['get'], detail=True)
    # 生成  ^books/(?P<pk>[^/.]+)/get_1/$ [name='book-get-1']
    def get_2(self, request, pk):
        book_obj = self.get_queryset()[:2] 
        ser = self.get_serializer(book_obj, many=True)
        return Response(ser.data)
    
#装饰器放在被装饰的函数中,methods:请求方式,detail:是否带pk

image-20221208183641841

image-20221208183956318

image-20221208183826571

posted @ 2022-12-12 17:24  ExpiredSaury  阅读(18)  评论(0编辑  收藏  举报