博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
django rest framework 解析器组件 接口设计,视图组件 (2)
阅读量:6005 次
发布时间:2019-06-20

本文共 5187 字,大约阅读时间需要 17 分钟。

1. 使用视图组件进行接口优化    1.1 使用视图组件的mixin进行接口逻辑优化       - 导入mixin          from rest_framework.mixinx import (             ListModelMix,             CreateModelMixin,             DestroyModelMixin,             UpdateModelMixin,             RetrieveModelMixin          )          from rest_framework.generics import GenericAPIView       - 定义序列化类       Class BookSerializer(serializers.ModelSerializer):             class Meta:                Book               fields = ()               extra_kwargs = {"field_name": {"write_only": True}}       - 导入序列化类       from .app_serializers import BookSerializer       - 定义视图类       class BookView(ListModelMix, CreateModelMixin, GenericAPIView):          # queryset和serializer_class是固定的写法           queryset = Book.objects.all()           serializer_class = BookSerializer           def get():              return self.list()           def post():              return self.create()       class BookFilterView(RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin, GenericAPIView):           queryset = Book.objects.all()          serializer_class = BookSerializer          def get():              return self.retrieve()          def delete():              return self.destroy()          def put():              return self.update()       注意:单条数据操作的url是这样的:re_path(r'books/(?P
\d+)/$, views.BookFilterView.as_view()) 实例:
1 # class BookView(ListModelMixin,CreateModelMixin,GenericAPIView): 2 #     queryset = Book.objects.all() 3 #     serializer_class = BookSerializer 4 #     def get(self,request, *args, **kwargs): 5 #         return self.list(request, *args, **kwargs) 6 #     def post(self,request, *args, **kwargs): 7 #         return self.create(request, *args, **kwargs) 8 # 9 # class BookFilterView(RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin, GenericAPIView):10 #     queryset = Book.objects.all()11 #     serializer_class = BookSerializer12 #     def put(self,request,*args,**kwargs):13 #         # 更改的时候区分一对多还是多对多14 #         return self.update(request,*args,**kwargs)15 #     def get(self,request,*args,**kwargs):16 #         return self.retrieve(request,*args,**kwargs)17 #     def delete(self,request,*args,**kwargs):18 #         return self.destroy(request,*args,**kwargs)
class类
1 class BookSerializer(serializers.ModelSerializer): 2     class Meta: 3         model = Book 4         fields = ('title', 5                   'price', 6                   'publish', 7                   'authors', 8                   'author_list', 9                   'publish_name',10                   'publish_city'11                   )12         # 如过不加会实在页面显示关联的数字13         extra_kwargs = {14             'publish': {
'write_only': True},15 'authors': {
'write_only': True}16 }17 18 publish_name = serializers.CharField(max_length=32, read_only=True, source='publish.name')19 publish_city = serializers.CharField(max_length=32, read_only=True, source='publish.city')20 21 author_list = serializers.SerializerMethodField()22 23 def get_author_list(self, book_obj):24 # 拿到queryset开始循环 [{}, {}, {}, {}]25 authors = list()26 27 for author in book_obj.authors.all():28 authors.append(author.name)29 30 return authors
引入ModelSerializer
1     #re_path(r'books/$', views.BookView.as_view()),2     #re_path(r'books/(?P
\d+)/$', views.BookFilterView.as_view()),
url

 

这时,会发现代码可以继续优化 1.2 使用视图组件的view进行接口逻辑优化    - 导入模块       from rest_framework import generics    - 写视图类       class BookView(generics.ListCreateAPIView)          queryset = Book.objects.all()          serializer_class = BookSerializer       class BookFilterView(generics.RetrieveUpdateDestroyAPIView):           queryset = Book.objects.all()          serializer_class = BookSerializer
1 # class BookView(generics.ListCreateAPIView):2 #     queryset = Book.objects.all()3 #     serializer_class = BookSerializer4 #5 # class BookFilterView(generics.RetrieveUpdateDestroyAPIView):6 #     queryset = Book.objects.all()7 #     serializer_class = BookSerializer
代码优化
1     # path("course/",views.BookView.as_view()),2     # re_path("course/(?P
\d+)/",views.BookFilterView.as_view())
url

 

1.3 使用视图组件的viewset进行接口逻辑优化    - 导入模块       from rest_framework.viewsets import ModelViewSet    - 设计url       re_path(r'books/$, views.BookView.as_view({
'get': 'list', 'post': 'create' })), re_path(r'books/(?P
\d+)/$', views.BookView.as_view({
'get': 'retrieve', 'delete': 'destroy', 'put': 'update' })) - 设计视图类 class BookView(ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer
1 class BookView(ModelViewSet):2     queryset = Book.objects.all()3     serializer_class = BookSerializer
最终版
1     re_path("course/$",views.BookView.as_view({2         "get":"list",3         "post":'create',4     })),5     re_path("course/(?P
\d+)/",views.BookView.as_view({6 'get':'retrieve',7 'put':"update",8 'delete':"destroy"9 }))
urls

 

 

转载于:https://www.cnblogs.com/zhangqing979797/p/10084424.html

你可能感兴趣的文章
正则与sed,grep,awk三剑客
查看>>
Uva 1025
查看>>
20165334 学习基础与c语言学习心得
查看>>
java中的IO流
查看>>
面向对象的程序
查看>>
Nginx安装与配置
查看>>
Nginx的负载均衡和高可用
查看>>
PHP分页原理
查看>>
dart 自己写一个文件编码器
查看>>
JS验证手机号
查看>>
安装centos
查看>>
myeclipse下jsp页面汉字不能保存问题
查看>>
存储系统层次结构
查看>>
《浏览器渲染原理及流程》学习笔记
查看>>
演示:思科IPS传感器的命令行初始配置(支持图型化管理)
查看>>
ubuntu安装和查看已安装
查看>>
基于GMap.Net的地图解决方案
查看>>
java list三种遍历方法性能比較
查看>>
Uva 10474 Where is the Marble?
查看>>
诊断一句SQL不走索引的原因
查看>>