• django rest framework 解析器组件 接口设计,视图组件 (2)


    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<pk>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 = BookSerializer
    12 #     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<pk>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 = BookSerializer
    4 #
    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<pk>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<pk>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<pk>d+)/",views.BookView.as_view({
    6         'get':'retrieve',
    7         'put':"update",
    8         'delete':"destroy"
    9     }))
    urls











  • 相关阅读:
    Codeforces Round #369 (Div. 2)
    poj3189二分图多重匹配
    a 标签传值
    phpStudy 虚拟主机
    wampserver 虚拟主机
    $file函数
    PHP脚本运行时间
    查询timestamp类型数据
    驼峰法
    easyUI导出数据
  • 原文地址:https://www.cnblogs.com/zhangqing979797/p/10084424.html
Copyright © 2020-2023  润新知