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, *args, **kwargs):

    return self.retrieve(request, *args, **kwargs)


  def post(self, request, *args, **kwargs):

    return self.create(request, *args, **kwargs)

 

路由

1

2

url(r'school/$', views.SchoolView.as_view()),

url(r'school/(?P\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

 

路由

1

2

3

4

5

6

7

8

9

10

url(r'school/$', views.SchoolView.as_view(actions={

  "get": "list",

  "post": "create",

})),

url(r'school/(?P\d+)/$', views.SchoolView.as_view(actions={

  'get': 'retrieve',

  'put': 'update',

  'patch': 'partial_update',

  'delete': 'destroy'

})),

高级路由

视图

同上

路由

1

2

3

4

5

from rest_framework.routers import DefaultRouter

 

router = DefaultRouter()

router.register(r'school', views.SchoolView)

urlpatterns += router.urls

精华:流程图

 

Django REST framework 视图和路由详解_第1张图片

你可能感兴趣的:(django)