Difference between APIView class and viewsets class?

前端 未结 4 1324
死守一世寂寞
死守一世寂寞 2021-02-03 22:36

What are the difference between APIView class and viewsets class ? I am following Django REST-framework official documentation. I think it lac

4条回答
  •  终归单人心
    2021-02-03 23:15

    APIView is the most basic class that you usually override when defining your REST view. You usually define your methods like get, put, delete and others check (http://www.cdrf.co/3.5/rest_framework.views/APIView.html). With APIView you define your view and you add it to your urls like so:

    # in views.py
    class MyAPIView(APIView):
         ... #here you put your logic check methods you can use
    #in urls.py
    url(r'^posts$', MyAPIView.as_view()), #List of all the posts
    

    Because certain things like getting the /post/4, deleting /post/4, getting all posts, updating and creating new post was so common DRF provides ViewSets.

    But first before you know ViewSets, let me tell you there are also Generic Classes that they do that things very good, but you need to provide full API end point like I did with my MyAPIView view (again for more info check http://www.cdrf.co/ or http://www.django-rest-framework.org/). So you would have to define your own urls path.

    But with ViewSets you create ViewSet that actually merges all the above described operations and also you don't need to define url path you usually use a router that makes paths for you like:

     # views.py
     class PostViewSet(ViewSet):  # here you subclass Viewset check methods you can override, you have also ModelViewSet,...
    
    
     # urls.py 
     router = routers.DefaultRouter()
     router.register(r'post', PostViewSet, base_name='Post')
    

提交回复
热议问题