关于DRF基类APIView提供的Request和Response对象的作用,可以看我的另一篇博文:https://www.cnblogs.com/chichung/p/9939864.html
综合使用:
from django.http import HttpResponse
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from user.models import Department
from user.serializers import DepartmentSerializer class DepartmentListAPIView(APIView):
def get(self,request):
"""查询多条数据"""
dep = Department.objects.all()
# 创建序列化器对象
serializer = DepartmentSerializer(instance=dep,many=True)
# 序列化:对象->字典
data_dict = serializer.data
# DRF的Response对象可以把字典转换为请求头指定的格式返回
return Response(data=data_dict) def post(self,request):
"""新增一条数据"""
# DRF的Request对象直接把接受到的值转换为字典
data_dict = request.data
# 创建序列化器对象
serializer = DepartmentSerializer(instance=None,data=data_dict)
# 校验校验不通过,抛异常(反序列化的功能)
serializer.is_valid(raise_exception=True)
# 反序列化,把字典的数据存进数据库
serializer.save()
# restful风格,新增要返回新增数据的那一列内容。用了序列化,把对象转换为字典,同时Response处理。
return Response(data=serializer.data) class DepartmentDetailAPIView(APIView):
def get(self,request,pk):
"""查询一条数据"""
# 查询出该条数据的对象
try:
dep = Department.objects.get(id=pk)
except Department.DoesNotExist:
return HttpResponse(status=status.HTTP_404_NOT_FOUND)
# 创建序列化器对象
serializer = DepartmentSerializer(instance=dep)
# 序列化,把对象转换为字典,同时Response根据请求头返回相应的格式
return Response(data=serializer.data) def post(self,request,pk):
"""修改部门"""
# DRF的Request对象直接把接受到的值转换为字典
data_dict = request.data
# 查询出要修改的数据
try:
dep = Department.objects.get(id=pk)
except Department.DoesNotExist:
return HttpResponse(status=404)
# 创建序列化器对象
serializer = DepartmentSerializer(instance=dep,data=data_dict)
# 反序列化,校验参数是否正确,若不正确,抛异常
serializer.is_valid(raise_exception=True)
# 反序列化,把字典的数据存进数据库
serializer.save()
# 序列化,把对象转换为字典。同时DRF的Response对象根据请求头返回相应的格式
return Response(serializer.data) def delete(self,request,pk):
"""删除一个部门"""
try:
dep = Department.objects.get(id=pk)
except Department.DoesNotExist:
return HttpResponse(status=404)
dep.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
相应路由的配置:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^departments$',views.DepartmentListAPIView.as_view()),
url(r'^departments/(?P<pk>\d+)$',views.DepartmentDetailAPIView.as_view())
]