传统Django中有基于类的视图,Drf中自然也有,目的都是实现功能的模块化继承,封装,减少重复代码。
首先在视图中新增下面代码:
# simpletool/views.py
from rest_framework.views import APIView
from simpletool.serializers import ToolDetailSerializer
from django.http import Http404
class simpletoolDetail(APIView):
def get_object(self,pk):
try:
return simpleTool.objects.get(pk=pk)
except:
raise Http404
def get(self,request,pk):
simpletool = self.get_object(pk)
serializer = ToolDetailSerializer(simpletool)
return Response(serializer.data)
def put(self,request,pk):
simpletool = self.get_object(pk)
serializer = ToolDetailSerializer(simpletool,data=request.data)
# 验证提交的数据是否合法,不合法则返回400
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):
simpletool = self.get_object(pk)
simpletool.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
上述代码为对tool的获取,修改,删除的3个方法,以及获取单个tool信息的方法,其中get(),put()就是有一部将对象序列化或者反序列化的步骤。
序列化这个概念与具体语言无关,python或者javascript对象转化为json都称为序列化,反正为反序列化。
现在来补充ToolDetailSerializer。与simpleTool列表不同,需要返回该工具所有完整的数据信息,所以需要给它新定义一个序列化器:
#simpletool/serializers.py
class ToolDetailSerializer(serializers.ModelSerializer):
class Meta:
model = simpleTool
fields = '__all__'
#simpletool/urls.py
urlpatterns = [
path('',views.tool_list,name='list'),
path('<int:pk>/',views.simpletoolDetail.as_view(),name='detail'),
]
httpie 测试
http http://127.0.0.1:8000/api/simpletool/1/
尝试修改工具名:
http PUT http://127.0.0.1:8000/api/simpletool/1/ title=test_tool
可以尝试将它删掉
http DELETE http://127.0.0.1:8000/api/simpletool/1/
1. 通用视图
实际上,增删改查为通用操作,所以可以用DRF提供的Mixin类直接集成对应的功能:
修改simpletoolDetail
#simpletool/views.py
from rest_framework import mixins
from rest_framework import generics
class simpletoolDetail(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView):
queryset = simpleTool.objects.all()
serializer_class = ToolDetailSerializer
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
我们可以让它更简单:
#simpletool/views.py
class simpletoolList(generics.ListCreateAPIView):
queryset = simpleTool.objects.all()
serializer_class = ToolListSerializer
class simpletoolDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = simpleTool.objects.all()
serializer_class = ToolDetailSerializer
#simpletool/urls.py
urlpatterns = [
path('',views.simpletoolList.as_view(),name='list'),
path('<int:pk>/',views.simpletoolDetail.as_view(),name='detail'),
]