Django REST framework 视图和路由详解

你虚度的今日是昨日逝去的人无限向往的明天。美丽的早晨,把压力释放,清凉的秋风,把欢乐吹响,温柔的阳光,把温馨点亮,轻松的心情,把幸福送上,早安!

DRF中的Request

在Django REST Framework中内置的Request类扩展了Django中的Request类,实现了很多方便的功能--如请求数据解析和认证等。

比如,区别于Django中的request从request.GET中获取URL参数,从request.POST中取某些情况下的POST数据。

在APIView中封装的request,就实现了请求数据的解析:

对于GET请求的参数我们通过request.query_params来获取。

对于POST请求、PUT请求的数据我们通过request.data来获取。

前提

序列化

from rest_framework import serializers
from app01 import models


class CommentSerializer(serializers.ModelSerializer):
  class Meta:
    model = models.Comment
    fields = "__all__"
    extra_kwargs = {
      "content": {"error_messages": {"required": "评论内容不能为空"}},
      "article": {"error_messages": {"required": "文章不能为空"}}
    }


class SchoolSerializer(serializers.ModelSerializer):
  class Meta:
    model = models.School
    fields = "__all__"

第一阶段:手垒代码

视图

from rest_framework.views import APIView
class SchoolView(APIView):
  def get(self, request, *args, **kwargs):
    query_set = models.School.objects.all()
    ser_obj = app01_serializers.SchoolSerializer(query_set, many=True)
    return Response(ser_obj.data)


class SchoolDetail(APIView):
  def get(self, request, pk, *args, **kwargs):
    obj = models.School.objects.filter(pk=pk).first()
    ser_obj = app01_serializers.SchoolSerializer(obj)
    return Response(ser_obj.data)

第二阶段:简单使用rest formwork自带混合类方法

视图

from rest_framework.generics import GenericAPIView # 公共类
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin # 混合类 必须与公共类搭配着使用

class SchoolView(GenericAPIView, mixins.ListModelMixin): # 查看学校列表
  queryset = models.School.objects.all()
  serializer_class = app01_serializers.SchoolSerializer

  def get(self, request, *args, **kwargs):
    return self.list(request, *args, **kwargs)


class SchoolDetail(GenericAPIView, mixins.RetrieveModelMixin, mixins.CreateModelMixin): # 创建,与具体查出某一条记录
  queryset = models.School.objects.all()
  serializer_class = app01_serializers.SchoolSerializer

  def get(self, request, pk, *args, **kwargs):
    return self.retrieve(request, pk, *args, **kwargs)

  def post(self, request, *args, **kwargs):
    return self.create(request, *args, **kwargs)

路由

url(r'school/$', views.SchoolView.as_view()),
url(r'school/(?P<pk>\d+)/$', views.SchoolDetail.as_view()),

第三阶段:使用rest formwork自带的通用类方法

视图

from rest_framework.generics import GenericAPIView, ListCreateAPIView, RetrieveUpdateAPIVie
class SchoolView(ListCreateAPIView): # 创建
  queryset = models.School.objects.all()
  serializer_class = app01_serializers.SchoolSerializer


class SchoolDetail(RetrieveUpdateDestroyAPIView): # 更新
  queryset = models.School.objects.all()
  serializer_class = app01_serializers.SchoolSerializer

路由同上

第四阶段:使用rest formwork自带的封装所有放的类,代码量最少,功能最全

视图

from rest_framework.viewsets import ModelViewSet # 里面封装了操作的所有方法,增删改查查
class SchoolView(ModelViewSet):
  queryset = models.School.objects.all()
  serializer_class = app01_serializers.SchoolSerializer

路由

url(r'school/$', views.SchoolView.as_view(actions={
  "get": "list",
  "post": "create",
})),
url(r'school/(?P<pk>\d+)/$', views.SchoolView.as_view(actions={
  'get': 'retrieve',
  'put': 'update',
  'patch': 'partial_update',
  'delete': 'destroy'
})),

高级路由

视图

同上

路由

from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'school', views.SchoolView)
urlpatterns += router.urls

精华:流程图

到此这篇关于Django REST framework 视图和路由详解就介绍到这了。青春的美丽与珍贵,就在于它的无邪与无瑕,在于它的可遇而不可求,在于它的永不重回。更多相关Django REST framework 视图和路由详解内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!

您可能有感兴趣的文章
简单了解Django ContentType内置组件

django表单的Widgets如何使用详解

django Admin文档生成器如何使用详解

django认证系统 Authentication如何使用详解

django 消息框架 message如何使用详解