1. 程式人生 > >DRF - 五個擴充套件類 - 輔助理解

DRF - 五個擴充套件類 - 輔助理解

from rest_framework.response import Response
from rest_framework.views import APIView

from booktest.models import BookInfo
from booktest.serializers import BookInfoSerializer


class BookInfoAPIView(APIView):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer

    # 來自於GenericAPIView
    def get_queryset(self):
        return self.queryset

    def get_serializer_class(self):
        return self.serializer_class

    def get_objects(self, pk):
        return self.get_queryset.get(pk=pk)

    # 來自於五個Mixin
    # 查所有
    def get(self, request):
        # books = BookInfo.objects.all()
        # serializer = BookInfoSerializer(books, many=True)
        books = self.get_queryset()
        serializer = self.get_serializer_class(books, many=True)
        return Response(serializer.data)

    # 查一個
    def get(self, request, pk):
        # book = BookInfo.objects.get(pk=pk)
        # book = BookInfo.objects.all().get(pk=pk)
        # serializer = BookInfoSerializer(book)
        book = self.get_objects(pk=pk)
        serializer = self.get_serializer_class(book)
        return Response(serializer.data)

    # 增加
    def post(self, request):
        # serializer = BookInfoSerializer(data=request.data)
        serializer = self.get_serializer_class(data=request.data)
        if not serializer.is_valid():
            return Response({"error": "錯誤"})
        serializer.save()
        return Response(serializer.data)

    # 修改
    def put(self, request, pk):
        # book = BookInfo.objects.get(pk=pk)
        # book = BookInfo.objects.all().get(pk=pk)
        # serializer = BookInfoSerializer(book)
        book = self.get_objects(pk=pk)
        serializer = self.get_serializer_class(book, data=request.data)
        if not serializer.is_valid():
            return Response({"error": "錯誤"})
        serializer.save()
        return Response(serializer.data)

    # 刪除
    def delete(self, request, pk):
        # book = BookInfo.objects.get(pk=pk)
        # book = BookInfo.objects.all().get(pk=pk)
        book = self.get_objects(pk=pk)
        book.delete()
        return Response("ok")