DRF之视图组件
2022/4/1 23:20:58
本文主要是介绍DRF之视图组件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
APIView
from rest_framework.views import APIView
类属性
renderer_classes, parser_classes
get方法,post方法,delete方法写法跟之前的View一样,只不过request对象变成了新的request丢下,比之前的View多了三大认证和全局异常处理
代码
class BookView(APIView): def get(self, request): book_list = Book.objects.all() ser = BookSerializers(instance=book_list, many=True) return Response(ser.data, headers={'name': 'zys'}) def post(self, request): ser = BookSerializers(data=request.data) if ser.is_valid(): ser.save() return Response({"code": 100, "msg": "新增成功", "data": ser.data}) return Response({"code": 101, "msg": "新增出错", "err": ser.errors}) class BookDataView(APIView): def get(self, request, pk): book = Book.objects.all().filter(pk=pk).frist() ser = BookSerializers(instance=book) return Response(ser.data) def put(self, request, pk): book = Book.objects.all().filter(pk=pk).first() ser = BookSerializers(instance=book, data=request.data) if ser.is_valid(): ser.save() return Response({"code": 100, "msg": "修改成功", "data": ser.data}) return Response({"code": 101, "msg": "修改出错", "err": ser.errors}) def delete(self, request, pk): Book.objects.filter(pk=pk).delete() return Response({"code": 100, "msg": "删除成功", })
GenericAPIView
继承了APIView ,多了属性和方法
from rest_framework.generics import GenericAPIView
属性
-queryset = None -serializer_class = None -lookup_field = 'pk' # 查询单条,分组分出来的参数,转换器对象参数的名字 -filter_backends # 过滤排序功能会用它 -pagination_class # 分页功能
方法
-get_queryset() # 获取要序列化的数据,后期可能会重写 -get_object() # 通过lookup_field查询的 -get_serializer() # 使用它序列化 -get_serializer_class() # 返回序列化类 ,后期可能重写
代码
class BookView(GenericAPIView): queryset = Book.objects.all() serializer_class = BookSerializers def get(self, request): obj = self.get_queryset() ser = self.get_serializer(instance=obj, many=True) return Response(ser.data) def post(self, request): ser = self.get_serializer(data=request.data) if ser.is_valid(): ser.save() return Response({"code": 100, "msg": "新增成功", "data": ser.data}) return Response({"code": 101, "msg": "新增出错", "err": ser.errors}) class BookDataView(GenericAPIView): queryset = Book.objects.all() serializer_class = BookSerializers def get(self, request, pk): obj = self.get_object() ser = self.get_serializer(instance=obj) return Response(ser.data) def put(self, request, pk): obj = self.get_object() ser = self.get_serializer(nstance=obj, data=request.data) if ser.is_valid(): ser.save() return Response({"code": 100, "msg": "修改成功", "data": ser.data}) return Response({"code": 101, "msg": "修改出错", "err": ser.errors}) def delete(self, request, pk): self.get_object().delete() return Response({"code": 100, "msg": "删除成功", })
5个视图扩展类(不是视图类,没有集成APIView,需要配合GenericAPIView)
新增,查询单条,查询所有,修改,删除
from rest_framework.mixins import CreateModelMixin,ListModelMixin,DestroyModelMixin,RetrieveModelMixin,UpdateModelMixin
代码
class PublishView(GenericAPIView,CreateModelMixin,ListModelMixin): queryset = Publish.objects.all() serializer_class = PublishSerializers def get(self, request): return super().list(request) def post(self, request): return super().create(request) class PublishDataView(GenericAPIView,DestroyModelMixin,RetrieveModelMixin,UpdateModelMixin): queryset = Publish.objects.all() serializer_class = PublishSerializers def get(self, request, *args, **kwargs): return super().retrieve(request,*args, **kwargs) def put(self, request, *args, **kwargs): return super().update(request,*args, **kwargs) def delete(self, request, *args, **kwargs): return super().destroy(request, *args, **kwargs)
9个视图子类---》是视图类
from rest_framework.generics import CreateAPIView, ListAPIView, DestroyAPIView, RetrieveAPIView, UpdateAPIView, \ ListCreateAPIView, RetrieveUpdateAPIView, RetrieveUpdateDestroyAPIView, RetrieveDestroyAPIView
代码
class PublishView(ListCreateAPIView): # 查询所有和新增接口 # class PublishView(CreateAPIView): # 新增接口 # class PublishView(ListAPIView): # 查询所有接口 queryset = Publish.objects.all() serializer_class = PublishSerializers # class PublishDataView(RetrieveUpdateDestroyAPIView): # 查询单条,删除,修改 # class PublishDataView(RetrieveAPIView): # 查询单条 # class PublishDataView(DestroyAPIView): # 删除 # class PublishDataView(UpdateAPIView): # 修改 # class PublishDataView(RetrieveDestroyAPIView): # 查询单条和删除 # class PublishDataView(RetrieveUpdateDestroyAPIView): # 查询单条和更新 class PublishDataView(UpdateAPIView, DestroyAPIView): # 更新和删除 queryset = Publish.objects.all() serializer_class = PublishSerializers
通过ViewSet写视图类
from rest_framework.viewsets import ModelViewSet,ReadOnlyModelViewSet
ModelViewSet
# 继承了5个试图扩展类+GenericViewSet(ViewSetMixin, generics.GenericAPIView) # ViewSetMixin控制了路由写法变了 # class PublishView(ModelViewSet): # 修改路由,5个接口 # queryset = Publish.objects.all() # serializer_class = PublishSerializers
ReadOnlyModelViewSet
class PublishView(ReadOnlyModelViewSet): # 修改路由,只读,查所有,查单个 queryset = Publish.objects.all() serializer_class = PublishSerializers
关于路由的两种书写方法
第一种
router = SimpleRouter() router.register('publish', views.PublishView, 'publish') urlpatterns = [ path('admin/', admin.site.urls), # path('publish/', views.PublishView.as_view()), # path('publish/<int:pk>', views.PublishDataView.as_view()), path('books/', views.BookView.as_view()), path('books/<int:pk>', views.BookDataView.as_view()), ] # 把路由加入到urlpatterns的列表中 # 第一种方法 # router.urls 他会自动生成 publish/ publish/<int:pk>print(router.urls)urlpatterns += router.urls # 两个列表相加
第二种
需导入include
from django.urls import path, include from app01 import views from rest_framework.routers import SimpleRouter router = SimpleRouter() router.register('publish', views.PublishView, 'publish') urlpatterns = [ path('admin/', admin.site.urls), # path('publish/', views.PublishView.as_view()), # path('publish/<int:pk>', views.PublishDataView.as_view()), path('books/', views.BookView.as_view()), path('books/<int:pk>', views.BookDataView.as_view()), path('api/v1/', include(router.urls)) # 前面可以加相加的东西 例如 'api/v1/' ]
关于路由书写的一些总结
# ViewSet=APIView+ViewSetMixin # GenericViewSet=GenericAPIView+ViewSetMixin from rest_framework.viewsets import ViewSet,GenericViewSet from rest_framework.viewsets import ViewSetMixin
以后只要想自动生成路由,必须继承ViewSetMixin及其子类,之前的写法可以沿用,只是如果要自动生成路由可以选择继承ViewSet,GenericViewSet
这篇关于DRF之视图组件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南