Difference between APIView class and viewsets class?

前端 未结 4 1309
死守一世寂寞
死守一世寂寞 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:06

    APIView allow us to define functions that match standard HTTP methods like GET, POST, PUT, PATCH, etc.

    Viewsets allow us to define functions that match to common API object actions like : LIST, CREATE, RETRIEVE, UPDATE, etc.

    Viewsets are also used to write logic to perform standard database operations and to interface with a database back-end. And are usually used for existing database model to manage predefined objects.

    0 讨论(0)
  • 2021-02-03 23:12

    The functions you add to the APIView are different than the functions you add to the ViewSet class.

    • APIView: you add functions for the particular HTTP method you want to support on your endpoint. Ex: GET, POST, PUT, PATCH, DELETE

    • ViewSet: you would add functions that represent actions that you'd perform on a typical API. Ex: LIST, CREATE, RETRIEVE, UPDATE

    0 讨论(0)
  • 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')
    
    0 讨论(0)
  • 2021-02-03 23:30

    Viewsets and APIView both allow us to write logic for end point but Viewsets dont define functions which map to HTTP methods instead map to common API object actions

    0 讨论(0)
提交回复
热议问题