DRF中APIView和viewsets的区别

DRF指代django rest framework

1.jpg

APIView是您在定义REST视图时通常会覆盖的最基本的类。您通常会定义诸如get,put,delete等方法。使用API​​View定义您的视图,然后将其添加到您的网址中,如下所示:

#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

因为某些事情比如getpost,删除帖子、获取所有帖子,更新和创建新帖子都是如此常见,DRF提供了Viewsets。使用ViewSets,您可以创建实际上合并所有上述操作的视图集,并且您也不需要定义url路径,通常使用路径为您创建路径:

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

参考文章

  • Difference between APIView class and viewsets class?

  • django rest framework apiview、viewset总结分析

你可能感兴趣的:(DRF中APIView和viewsets的区别)