码迷,mamicode.com
首页 > 其他好文 > 详细

REST framework组件-视图

时间:2018-09-02 14:33:51      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:cts   ram   let   mod   ret   frame   ted   *args   EAP   

mixin类编写视图

class BookViewSet(mixins.ListModelMixin,
                  mixins.CreateModelMixin,
                  generics.GenericAPIView):

    queryset = Book.objects.all()
    serializer_class = BookSerializers

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)



class BookDetailViewSet(mixins.RetrieveModelMixin,
                    mixins.UpdateModelMixin,
                    mixins.DestroyModelMixin,
                    generics.GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializers

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

使用通用的基于类的视图

from rest_framework import mixins
from rest_framework import generics

class BookViewSet(generics.ListCreateAPIView):

    queryset = Book.objects.all()
    serializer_class = BookSerializers

class BookDetailViewSet(generics.RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializers

viewsets.ModelViewSet

url.py:

    path(books/, views.BookViewSet.as_view({get: list, post: create})),
    re_path(r^books/(?P<pk>\d+)$, views.BookViewSet.as_view({
        get:retrieve,
        put: update,
        delete: destroy}))

views.py

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

 

REST framework组件-视图

标签:cts   ram   let   mod   ret   frame   ted   *args   EAP   

原文地址:https://www.cnblogs.com/lullaby/p/9573597.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!