View Set ViewSets

View Set ViewSets

Using the set of views ViewSet, a series of logic operations can be associated into a class:

  • list () provides a set of data
  • retrieve () provides a single data
  • create () to create data
  • update () to save data
  • destory () to delete data

ViewSet viewset not implemented class get (), post () method and the like, but to realize the operation action as list (), create () and the like.

Using the set of views only as_view () method when the only action the operation mode corresponding to the specific request. Such as:

class BookInfoViewSet(viewsets.ViewSet):

    def list(self, request):
        books = BookInfo.objects.all()
        serializer = BookInfoSerializer(books, many=True)
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        try:
            books = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        serializer = BookInfoSerializer(books)
        return Response(serializer.data)

When setting the route, we can do this

urlpatterns = [
    url(r'^books/$', BookInfoViewSet.as_view({'get':'list'}),
    url(r'^books/(?P<pk>\d+)/$', BookInfoViewSet.as_view({'get': 'retrieve'})
]

Common View Set parent

1) ViewSet

Inherited from APIViewthe ViewSetMixinrole also APIView essentially similar, it provides authentication, verification authority, traffic management.

Mapping processing: ViewSet achieved when an incoming call as_view () dictionary (e.g., { 'list' 'get'}) mainly through inheritance ViewSetMixin.

In ViewSet, the action does not provide any method of action, we need to implement their own action methods.

2)GenericViewSet

Use ViewSet usually not easy, because the list, retrieve, create, update, destory other methods need to write your own, but these methods with the same name, said before the extension class Mixin provided, so we can re-extend the class through inheritance Mixin with these methods without having to write your own. But Mixin dependence and extension classes GenericAPIView, so it needs to inherit GenericAPIView.

GenericViewSet helped us complete this work inheritance, inherited from GenericAPIViewand ViewSetMixin, in the realization of the dictionary when incoming calls as_view () (such as {'get':'list'}) the mapping process to work, while also providing a GenericAPIViewbasis for the methods provided, can directly extend the class with Mixin use.

For example:

from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action

class BookInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer

The definition of url

urlpatterns = [
    url(r'^books/$', views.BookInfoViewSet.as_view({'get': 'list'})),
    url(r'^books/(?P<pk>\d+)/$', views.BookInfoViewSet.as_view({'get': 'retrieve'})),
]

3)ModelViewSet

Inherited from GenericViewSet, and including ListModelMixin, RetrieveModelMixin, CreateModelMixin, UpdateModelMixin, DestoryModelMixin.

4)ReadOnlyModelViewSet

Inherited from GenericViewSet, and including ListModelMixin, RetrieveModelMixin.

Viewset define additional action action

In view of the concentration, in addition to the default method of operation, may further add custom actions.

For example:

from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action

class BookInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer

    def latest(self, request):
        """
        返回最新的图书信息
        """
        book = BookInfo.objects.latest('id')
        serializer = self.get_serializer(book)
        return Response(serializer.data)

    def read(self, request, pk):
        """
        修改图书的阅读量数据
        """
        book = self.get_object()
        book.bread = request.data.get('read')
        book.save()
        serializer = self.get_serializer(book)
        return Response(serializer.data)

The definition of url

urlpatterns = [
    url(r'^books/$', views.BookInfoViewSet.as_view({'get': 'list'})),
    url(r'^books/latest/$', views.BookInfoViewSet.as_view({'get': 'latest'})),
    url(r'^books/(?P<pk>\d+)/$', views.BookInfoViewSet.as_view({'get': 'retrieve'})),
    url(r'^books/(?P<pk>\d+)/read/$', views.BookInfoViewSet.as_view({'put': 'read'})),
]

action properties

In view of the focus, we may be obtained by action action action object properties when the current request is which set of views.

E.g:

from rest_framework.viewsets import ModelViewSet,ReadOnlyModelViewSet
from booktest.models import BookInfo
from .serializers import BookInfoModelSerializer
from rest_framework.response import Response
class BookInfoModelViewSet(ModelViewSet):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoModelSerializer

    def get_top_5(self,request):
        """获取评论值最多的5条数据"""
        # 操作数据库
        print(self.action) # 获取本次请求的视图方法名
        
        
通过路由访问到当前方法中.可以看到本次的action就是请求的方法名

Guess you like

Origin www.cnblogs.com/SkyOceanchen/p/11922978.html