• 周末作业 7/11


    1 视图类继承GenericAPIView,get方法,post方法,用的序列化类不一样

    views.py

    from app01.utils.MGenricAPIView import MGenricAPIView
    
    class BookView3(MGenricAPIView):
        # queryset要传queryset对象,查询了所有的图书
        # serializer_class使用哪个序列化类来序列化这堆数据
        queryset = Book.objects.all()
        serializer_class = {"get": BookSerializer2, "post": BookSerializer}
    
        def get(self, request):
            book_list = self.get_queryset()
            serializer = self.get_serializer(book_list,many=True)
            return Response(serializer.data)
    
        def post(self, request):
            serializer = self.get_serializer(data=request.data)
    
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data)
            else:
                print(serializer.data)
                print(serializer.errors)
    
                return Response({'status': 101, 'msg': '添加失败'})

    MGenricAPIView.py

    from rest_framework.generics import GenericAPIView
    
    
    class MGenricAPIView(GenericAPIView):
        def get_serializer_class(self):
            # print(type(self.serializer_class),self.serializer_class.get("get"))
            data_dic = self.serializer_class
            if self.request.method == 'POST':
                self.serializer_class = data_dic.get("post")
                return self.serializer_class
            self.serializer_class = data_dic.get("get")
            return self.serializer_class

    urls.py

    from django.contrib import admin
    from django.urls import path
    from app01 import views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('books3/', views.BookView3.as_view()),
    ]
  • 相关阅读:
    sonarque下载和安装使用
    npm install appium
    WIn10 电脑运行Docker
    AngularJs Type error : Cannot read property 'childNodes' of undefined
    Angular ui-route介绍
    Thymeleaf的模板使用介绍
    IntelliJ IDEA IDEA 2018 激活注册码
    session和cookies
    springmvc中的拦截器interceptor用法
    实现mapper接口注入的两种方式,以及后台的使用区别
  • 原文地址:https://www.cnblogs.com/baicai37/p/13290590.html
Copyright © 2020-2023  润新知