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__"
通用类
视图
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
路由
url(r'school/$', views.SchoolView.as_view()), url(r'school/(?P<pk>d+)/$', views.SchoolDetail.as_view()),
使用视图集
视图
class SchoolView(ModelViewSet): queryset = models.School.objects.all() serializer_class = app01_serializers.SchoolSerializer
路由
url(r'school/$', views.SchoolView.as_view({ "get": "list", "post": "create", })), url(r'school/(?P<pk>d+)/$', views.SchoolView.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' })),
高级路由
视图
class SchoolView(ModelViewSet): queryset = models.School.objects.all() serializer_class = app01_serializers.SchoolSerializer
路由
from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'school', views.SchoolView) urlpatterns += router.urls
类的继承图