rest_framework之视图

对请求响应到的视图函数的处理, 及视图函数的封装

注:mySer.BookSerializers为序列化的类

一, 对之前的增删改查进行封装

方式一:

from rest_framework.mixins import DestroyModelMixin, CreateModelMixin, ListModelMixin, UpdateModelMixin, RetrieveModelMixin
from rest_framework.generics import GenericAPIView


class Book(CreateModelMixin, ListModelMixin, GenericAPIView):
    queryset = models.Book.objects.all()
    serializer_class = mySer.BookSerializers

    def get(self, request):
        return self.list(request)

    def post(self, request):
        return self.create(request)


class BookDetail(GenericAPIView, UpdateModelMixin, RetrieveModelMixin, DestroyModelMixin):
    queryset = models.Book.objects.all()
    serializer_class = mySer.BookSerializers

    def get(self, request, pk):
        return self.retrieve(request, pk)

    def put(self, request, pk):
        return self.update(request, pk)

    def delete(self, request, pk):
        return self.destroy(request, pk)

路由:    
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^book/$', views.Book.as_view()),
    url(r'^book/(?P\d+)', views.BookDetail.as_view()),
]

方式二:

from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView

class Book(ListCreateAPIView):
    queryset = models.Book.objects.all()
    serializer_class = mySer.BookSerializers

class BookDetail(RetrieveUpdateDestroyAPIView):
    queryset = models.Book.objects.all()
    serializer_class = mySer.BookSerializers
    
路由:    
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^book/$', views.Book.as_view()),
    url(r'^book/(?P\d+)', views.BookDetail.as_view()),
]

方式三: (不推荐)

from rest_framework.viewsets import ModelViewSet

class Book(ModelViewSet):
    queryset = models.Book.objects.all()
    serializer_class = mySer.BookSerializers
    
    
路由:
urlpatterns = [
    url(r'^book/$', views.Book.as_view({'get': 'list', 'post': 'create'})),
    url(r'^book/(?P\d+)', views.Book.as_view(
        {'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
]

二, 魔法类 - ViewSetMixin

可以实现, 增删改查与查单条数据用一个视图类

在路由里加上{'get': 'test1', 'post': 'test2'}实现get请求响应test1函数,post请求响应test2函数

from rest_framework.viewsets import ViewSetMixin
from rest_framework.views import APIView

#继承的时候两个类的顺序不能反
class Test(ViewSetMixin,APIView):
    def test1(self, request):
        return JsonResponse({"test1": "test1"})

    def test2(self, request):
        return JsonResponse({"test2": "test2"})

    def test3(self, request,pk):
        return JsonResponse({"test3": "test3"})

    def test4(self, request,pk):
        return JsonResponse({"test4": "test4"})

    def test5(self, request,pk):
        return JsonResponse({"test5": "test5"})
    
路由:
urlpatterns = [
    url(r'^test/$', views.Test.as_view({'get': 'test1', 'post': 'test2'})),
    url(r'^test/(?P\d+)', views.Test.as_view(
        {'get': 'test3', 'put': 'test4', 'delete': 'test5'})),
]

你可能感兴趣的:(rest_framework之视图)