GenericAPIView
# 基于GenericAPIView
from rest_framework.generics import GenericAPIView
?
?
class BookAPIView(GenericAPIView): # 需要传入两个参数queryset,serializer_class
queryset = models.Books.objects # 需要传入queryset对象
serializer_class = BookSerializers # 指定使用那个序列化器
?
def get(self, request, pk): # 单本书籍的查询
response_dic = utils.MyResponse() # 实例化自定义工具类中的response类
book = self.get_object() # 获取当前查询图书对象,单个对象使用get_object
book_ser = self.get_serializer(instance=book) # 实例化自定义序列化器
response_dic.data = book_ser.data # 将数据传入
return Response(response_dic.dict)
?
def put(self, request, pk): # 单本书籍的修改
response_dic = utils.MyResponse() # 实例化自定义类
book = self.get_object() # 获取要修改的书籍
book_ser = self.get_serializer(instance=book, data=request.data) # 传入要修改的对象和数据
if book_ser.is_valid(): # 校验数据
book_ser.save() # 保存数据,需要在自定义序列化器中重写update方法
response_dic.data = book_ser.data
else:
response_dic.code = 99
response_dic.msg = ‘校验不通过‘
response_dic.data = book_ser.errors # 返回校验结果
return Response(response_dic.dict)
?
def delete(self, request, pk): # 删除指定图书
response_dic = utils.MyResponse()
self.get_object().delete()
return Response(response_dic.dict)
?
?
# 查询全部书籍、增加新书籍
class BooksAPIView(GenericAPIView):
queryset = models.Books.objects
serializer_class = BookSerializers
?
def get(self, request):
response_dic = utils.MyResponse()
book = self.get_queryset() # 获得全部book对象,多个对象使用get_queryset
book_ser = self.get_serializer(instance=book, many=True) # 序列化多条数据需要加上many参数
response_dic.data = book_ser.data
return Response(response_dic.dict)
?
def post(self, request):
response_dic = utils.MyResponse()
book_ser = self.get_serializer(data=request.data) # 新增时不需要传入修改对象,传入新增数据
if book_ser.is_valid(): # 校验
book_ser.save()
response_dic.data = book_ser.data
else:
response_dic.code = 99
response_dic.msg = ‘校验失败‘