action装饰器的使用

from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from book_drf.serializer import BookSerializer
from books.models import BookInfo


class Books(ModelViewSet):
    queryset = BookInfo.objects.all()  # 指定当前类视图使用的查询集数据
    serializer_class = BookSerializer  # 指定当前类视图使用的序列化器

    # 有@action 可以自动生成匹配 lastdata的路由
    # 如果detail=True 就可以生成匹配pk值的路由
    @action(methods=['get'], detail=True)
    def lastdata(self, request, pk):
        # 调用的方式 /books_drf/6/lastdata/
        # 路由配置方法 url(r'^books_drf/(?P<pk>\d+)/lastdata/$', viewset_view.BookDRFView.as_view({'get': 'lastdata'})),
        book = self.get_object()  # 从查询集中获取指定的单一数据对象
        ser = self.get_serializer(book)
        return Response(ser.data)

urls配置路由python代码如下:

from rest_framework.routers import SimpleRouter
from . import modelviewset_view
urlpatterns = []

router = SimpleRouter()
router.register('books_drf', modelviewset_view.Books, basename='books')
print(router.urls)
urlpatterns += router.urls

SimpleRouter自动生成的路由print如下: 

[<URLPattern '^books_drf/$' [name='books-list']>, 
<URLPattern '^books_drf/(?P<pk>[^/.]+)/$' [name='books-detail']>, 
<URLPattern '^books_drf/(?P<pk>[^/.]+)/lastdata/$' [name='books-lastdata']>]