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()), ]