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 = '校驗失敗'
response_dic.data = 