其他分享
首页 > 其他分享> > 类视图(APIView)

类视图(APIView)

作者:互联网

from rest_framework.views import APIView
from meituan.models import Merchant
from django.http import Http404
from .serializers import MerchantSerializer
from rest_framework.response import Response
from rest_framework import status

###################### APIView的代码 ######################
class MerchantView(APIView):
    """
    检索, 更新和删除一个merchant实例对象.
    """
    def get_object(self, pk):
        try:
            return Merchant.objects.get(pk=pk)
        except Merchant.DoesNotExist:
            raise Http404

    def get(self, request, pk=None):
        if pk:
            merchant= self.get_object(pk)
            serializer = MerchantSerializer(merchant)
            return Response(serializer.data)
        else:
            queryset = Merchant.objects.all()
            serializer = MerchantSerializer(instance=queryset,many=True)
            return Response(serializer.data)

    def put(self, request, pk):
        merchant = self.get_object(pk)
        serializer = MerchantSerializer(merchant, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk):
        merchant= self.get_object(pk)
        merchant.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
from django.urls import path
from .views import MerchantView

app_name = 'classview'
urlpatterns = [
    # 列表:/merchant/ get
    # 新增:/merchant/ post
    # 详情:/merchant/[pk]/ get
    # 修改:/merchant/[pk]/ put
    # 删除:/merchant/[pk]/ delete
    path('merchant/',MerchantView.as_view()),
    path('merchant/<int:pk>/',MerchantView.as_view()),
]

标签:merchant,get,self,APIView,视图,import,pk,serializer
来源: https://www.cnblogs.com/xshan/p/14193392.html