067.Python框架Django之DRF视图类
一 关于视图类的一下概念
drf除了在数据序列化部分简写代码以外,还在视图中提供了简写操作。所以在django原有的django.views.View类基础上,drf封装了多个子类出来提供给我们使用。
Django REST framwork 提供的视图的主要作用:
- 控制序列化器的执行(检验、保存、转换数据)
- 控制数据库查询的执行
- 调用请求类和响应类(这两个类也是由drf帮我们再次扩展了一些功能类)。
请求与响应
1.1 Request请求
REST framework 传入视图的request对象不再是Django默认的HttpRequest对象,而是REST framework提供的扩展了HttpRequest类的Request类的对象。
REST framework 提供了Parser解析器,在接收到请求后会自动根据Content-Type指明的请求数据类型(如JSON、表单等)将请求数据进行parse解析,解析为类字典[QueryDict]对象保存到Request对象中。
Request对象的数据是自动根据前端发送数据的格式进行解析之后的结果。
包含了解析之后的文件和非文件数据
包含了对POST、PUT、PATCH请求方式解析后的数据
利用了REST framework的parsers解析器,不仅支持表单类型数据,也支持JSON数据
request.query_params与Django标准的 request.GET 相同,只是更换了更正确的名称而已。
1.2 Response响应
REST framework提供了一个响应类Response,使用该类构造响应对象时,响应的具体数据内容会被转换(render渲染)成符合前端需求的类型。
REST framework提供了 Renderer 渲染器,用来根据请求头中的Accept(接收数据类型声明)来自动转换响应数据到对应格式。如果前端请求中未进行Accept声明,则会采用默认方式处理响应数据,我们可以通过配置来修改默认响应格式。
可以在rest_framework.settings查找所有的drf默认配置项
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( # 默认响应渲染类 'rest_framework.renderers.JSONRenderer', # json渲染器 'rest_framework.renderers.BrowsableAPIRenderer', # 浏览API渲染器 ) }
构造方式:
Response(data, status=None, template_name=None, headers=None, content_type=None)
data数据不要是render处理之后的数据,只需传递python的内建类型数据即可,REST framework会使用 renderer 渲染器处理data。
data不能是复杂结构的数据,如Django的模型类对象,对于这样的数据我们可以使用 Serializer 序列化器序列化处理后(转为了Python字典类型)再传递给data参数。
参数说明:
-
data: 为响应准备的序列化处理后的数据;
-
status: 状态码,默认200;
-
template_name: 模板名称,如果使用HTMLRenderer 时需指明;
-
headers: 用于存放响应头信息的字典;
-
content_type: 响应数据的Content-Type,通常此参数无需传递,REST framework会根据前端所需类型数据来设置该参数。
- 客户端错误---4XX
- 服务器错误---5XX
二 视图
REST framework 提供了众多的通用视图基类与扩展类,以简化视图的编写。
2.1 APIView和View区别
Django REST framwork 提供的视图的主要作用:
- 控制数据库查询的执行
APIView 与View的不同之处在于:
- 传入到视图方法中的是REST framework的request对象,而不是Django的HttpRequest对象;
- 视图方法可以返回REST framework的Response对象
- 任何APIException异常都会被捕获到,并且处理成合适的响应信息;
- 在进行dispatch()分发前,会对请求进行身份认证、权限检查、流量控制。
支持定义的类属性
- authentication_classes 列表或元祖,身份认证类
- permissoin_classes 列表或元祖,权限检查类
- throttle_classes 列表或元祖,流量控制类
在APIView中仍以常规的类视图定义方法来实现get() 、post() 或者其他请求方式的方法。
对比APIview和view的区别
创建新的应用
(drfdemo) root@darren-virtual-machine:~/PycharmProjects/drfdemo/drf_demo# python3 manage.py startapp req
注册app
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'students.apps.StudentsConfig', 'ser.apps.SerConfig', 'req.apps.ReqConfig', ]
配置路由分发
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('student/',include("students.urls")), path('ser/',include("ser.urls")), path('req/', include("req.urls")), ]
(drfdemo) root@darren-virtual-machine:~/PycharmProjects/drfdemo/drf_demo# vim req/urls.py
from django.urls import path,re_path from req import views urlpatterns = [ path('student1/',views.Student1View.as_view()), path('student2/', views.Student2APIView.as_view()), ]
视图文件
from django.shortcuts import render,HttpResponse from django.views import View # Create your views here. class Student1View(View): def get(self,request): print(request) print(type(request)) return HttpResponse("view1") class Student2APIView(View): def get(self,request): print(request) print(type(request)) return HttpResponse("view2")
访问对比
http://127.0.0.1:8000/req/student1/
打印结果
<WSGIRequest: GET '/req/student1/'> <class 'django.core.handlers.wsgi.WSGIRequest'>
http://127.0.0.1:8000/req/student2/
打印结果
<rest_framework.request.Request object at 0x7fc71b7c9860> <class 'rest_framework.request.Request'>
加参数访问,提取参数结果
from django.shortcuts import render,HttpResponse from django.views import View from rest_framework.views import APIView # Create your views here. class Student1View(View): def get(self,request): print(request.GET) print(type(request)) return HttpResponse("view1") class Student2APIView(APIView): def get(self,request): print(request.query_params) print(type(request)) return HttpResponse("view2")
访问http://127.0.0.1:8000/req/student1/?name=alex&age=20 和http://127.0.0.1:8000/req/student2/?name=alex&age=20
打印结果
<QueryDict: {'name': ['alex'], 'age': ['20']}> <class 'django.core.handlers.wsgi.WSGIRequest'> [20/Apr/2020 12:22:01] "GET /req/student1/?name=alex&age=20 HTTP/1.1" 200 5 [20/Apr/2020 12:22:08] "GET /req/student2/?name=alex&age=20 HTTP/1.1" 200 5 <QueryDict: {'name': ['alex'], 'age': ['20']}> <class 'rest_framework.request.Request'>
使用responbe定义状态码响应
from django.shortcuts import render,HttpResponse from django.views import View from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status # Create your views here. class Student1View(View): def get(self,request): print(request.GET) print(type(request)) return HttpResponse("view1") class Student2APIView(APIView): def get(self,request): print(request.query_params) print(type(request)) return Response("view2",status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION)
访问http://127.0.0.1:8000/req/student2/?name=alex&age=20
添加头部信息
from django.shortcuts import render,HttpResponse from django.views import View from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status # Create your views here. class Student1View(View): def get(self,request): print(request.GET) print(type(request)) return HttpResponse("view1") class Student2APIView(APIView): def get(self,request): print(request.query_params) print(type(request)) return Response("view2",status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION,headers={"name":"alex"})
访问结果
使用API借口实现功能
使用APIView提供学生信息的5个API接口 GET /req/student3/ # 获取全部数据 POST /req/student3/ # 添加数据 GET /req/student3/(?P<pk>\d+) # 获取一条数据 PUT /req/student3/(?P<pk>\d+) # 更新一条数据 DELETE /req/student3/(?P<pk>\d+) # 删除一条数据
url路由配置
from django.urls import path,re_path from req import views urlpatterns = [ path('student1/',views.Student1View.as_view()), path('student2/', views.Student2APIView.as_view()), # 使用APIView path("student3/", views.Student3APIView.as_view()), re_path(r"^student3/(?P<pk>\d+)/$", views.Student4APIView.as_view()), ]
新建serializer文件,序列操作
(drfdemo) root@darren-virtual-machine:~/PycharmProjects/drfdemo/drf_demo# vim req/serializers.py
from students.models import Student from rest_framework import serializers class StudentModelSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ["id", "name", "age", "sex"] extra_kwargs = { "name": {"max_length": 10, "min_length": 4}, "age": {"max_value": 150, "min_value": 0}, } def validate_name(self, data): if data == "root": raise serializers.ValidationError("用户名不能为root!") return data def validate(self, attrs): name = attrs.get('name') age = attrs.get('age') if name == "alex" and age == 22: raise serializers.ValidationError("alex在22时的故事。。。") return attrs
写视图文件
from django.shortcuts import render,HttpResponse from django.views import View from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status # Create your views here. class Student1View(View): def get(self,request): print(request.GET) print(type(request)) return HttpResponse("view1") class Student2APIView(APIView): def get(self,request): print(request.query_params) print(type(request)) return Response("view2",status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION,headers={"name":"alex"}) from students.models import Student from req.serializers import StudentModelSerializer class Student3APIView(APIView): def get(self, request): """获取所有数据""" student_list = Student.objects.all() # 序列化操作 serializer = StudentModelSerializer(instance=student_list, many=True) return Response(serializer.data) def post(self, request): # 获取用户提交的数据 data_dict = request.data # 实例化序列化器对象 serializer = StudentModelSerializer(data=data_dict) # 数据校验 serializer.is_valid(raise_exception=True) # 保存数据 serializer.save() return Response(serializer.validated_data) class Student4APIView(APIView): def get(self, request, pk): # 过滤pk对应的学生对象 student_obj = Student.objects.get(pk=pk) serializer = StudentModelSerializer(instance=student_obj) return Response(serializer.data) def put(self, request, pk): # 过滤pk对应的学生对象 student_obj = Student.objects.get(pk=pk) # 获取用户提交的数据 data_dict = request.data serializer = StudentModelSerializer(instance=student_obj, data=data_dict) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.validated_data) def delete(self, request, pk): Student.objects.filter(pk=pk).delete() return Response(status=status.HTTP_204_NO_CONTENT)
使用POSTMAN调试
获取所有
添加数据
查看数据库
修改数据
查看数据库
删除
数据库查看
状态码
2.2 GenericAPIView(通用视图类)
from
rest_framework.generics
import
GenericAPIView
继承自APIView,主要增加了操作序列化器和数据库查询的方法,作用是为下面Mixin扩展类的执行提供方法支持。通常在使用时,可搭配一个或多个Mixin扩展类。
提供的关于序列化器使用的属性与方法
方法:get_serializer_class(self)
- 当出现一个视图类中调用多个序列化器时,那么可以通过条件判断在get_serializer_class方法中通过返回不同的序列化器类名就可以让视图方法执行不同的序列化器对象了。
- 返回序列化器类,默认返回serializer_class,可以重写,例如:
def get_serializer_class(self): if self.request.user.is_staff: return FullAccountSerializer return BasicAccountSerializer
get_serializer(self, args, *kwargs)
返回序列化器对象,主要用来提供给Mixin扩展类使用,如果我们在视图中想要获取序列化器对象,也可以直接调用此方法。
提供的关于数据库查询的属性与方法
属性:queryset 指明使用的数据查询集
返回视图使用的查询集,主要用来提供给Mixin扩展类使用,是列表视图与详情视图获取数据的基础,默认返回queryset属性,可以重写,例如:
def get_queryset(self): user = self.request.user return user.accounts.all()
返回详情视图所需的模型类数据对象,主要用来提供给Mixin扩展类使用。
在试图中可以调用该方法获取详情信息的模型类对象。
其他可以设置的属性
- pagination_class 指明分页控制类
- filter_backends 指明过滤控制后端
2.3 GenericAPIView实现接口
url路由
from django.urls import path,re_path from req import views urlpatterns = [ path('student1/',views.Student1View.as_view()), path('student2/', views.Student2APIView.as_view()), # 使用APIView path("student3/", views.Student3APIView.as_view()), re_path(r"^student3/(?P<pk>\d+)/$", views.Student4APIView.as_view()), # 使用GenericAPIView path("student4/", views.Student5GenericAPIView.as_view()), re_path(r"^student4/(?P<pk>\d+)/$", views.Student6GenericAPIView.as_view()), ]
实现5个功能
使用GenericAPIView提供学生信息的5个API接口 GET /req/student4/ # 获取全部数据 POST /req/student4/ # 添加数据 GET /req/student4/(?P<pk>\d+) # 获取一条数据 PUT /req/student4/(?P<pk>\d+) # 更新一条数据 DELETE /req/student4/(?P<pk>\d+) # 删除一条数据
视图文件
from django.shortcuts import render,HttpResponse from django.views import View from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status # Create your views here. class Student1View(View): def get(self,request): print(request.GET) print(type(request)) return HttpResponse("view1") class Student2APIView(APIView): def get(self,request): print(request.query_params) print(type(request)) return Response("view2",status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION,headers={"name":"alex"}) from students.models import Student from req.serializers import StudentModelSerializer class Student3APIView(APIView): def get(self, request): """获取所有数据""" student_list = Student.objects.all() # 序列化操作 serializer = StudentModelSerializer(instance=student_list, many=True) return Response(serializer.data) def post(self, request): # 获取用户提交的数据 data_dict = request.data # 实例化序列化器对象 serializer = StudentModelSerializer(data=data_dict) # 数据校验 serializer.is_valid(raise_exception=True) # 保存数据 serializer.save() return Response(serializer.validated_data) class Student4APIView(APIView): def get(self, request, pk): # 过滤pk对应的学生对象 student_obj = Student.objects.get(pk=pk) serializer = StudentModelSerializer(instance=student_obj) return Response(serializer.data) def put(self, request, pk): # 过滤pk对应的学生对象 student_obj = Student.objects.get(pk=pk) # 获取用户提交的数据 data_dict = request.data serializer = StudentModelSerializer(instance=student_obj, data=data_dict) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.validated_data) def delete(self, request, pk): Student.objects.filter(pk=pk).delete() return Response(status=status.HTTP_204_NO_CONTENT) from rest_framework.generics import GenericAPIView class Student5GenericAPIView(GenericAPIView): # 当前视图类中操作的公共数据,先从数据库查询出来 queryset = Student.objects.all() # 设置类视图中所有方法共有调用的序列化器类 serializer_class = StudentModelSerializer def get(self, request): # 获取模型数据 student_list = self.get_queryset() # 调用序列化器 serializer = self.get_serializer(instance=student_list, many=True) return Response(serializer.data) def post(self, request): """新增数据""" # 获取用户提交的数据并实例化序列化器对象 serializer = self.get_serializer(data=request.data) # 数据校验 serializer.is_valid(raise_exception=True) # 保存数据 serializer.save() return Response(serializer.data) class Student6GenericAPIView(GenericAPIView): # 当前视图类中操作的公共数据,先从数据库查询出来 queryset = Student.objects.all() # 设置类视图中所有方法共有调用的序列化器类 serializer_class = StudentModelSerializer def get(self, request, pk): """参数pk名,必须要叫pk,否则会报错。""" # 获取模型对象 instance = self.get_object() serializer = self.get_serializer(instance=instance) return Response(serializer.data) def put(self, request, pk): instance = self.get_object() serializer = self.get_serializer(instance=instance, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) def delete(self, request, pk): # 获取模型对象 instance = self.get_object() # 删除模型对象 instance.delete() return Response(status=status.HTTP_204_NO_CONTENT)
使用POSTMAN调试
获取所有
添加数据
数据库查看
修改数据
查看数据库
删除
数据库
2.4 五个视图扩展类
使用GenericAPIView结合视图Mixin扩展类,快速实现数据接口的APIView ListModelMixin 实现查询所有数据功能 CreateModelMixin 实现添加数据的功能 RetrieveModelMixin 实现查询一条数据功能 UpdateModelMixin 更新一条数据的功能 DestroyModelMixin 删除一条数据的功能
在req应用下的urls.py文件:
from django.urls import path,re_path from req import views urlpatterns = [ path('student1/',views.Student1View.as_view()), path('student2/', views.Student2APIView.as_view()), # 使用APIView path("student3/", views.Student3APIView.as_view()), re_path(r"^student3/(?P<pk>\d+)/$", views.Student4APIView.as_view()), # 使用GenericAPIView path("student4/", views.Student5GenericAPIView.as_view()), re_path(r"^student4/(?P<pk>\d+)/$", views.Student6GenericAPIView.as_view()), # 使用GenericAPIView,结合Mixin的扩展类 path("student5/", views.Student7GenericAPIView.as_view()), re_path(r"^student5/(?P<pk>\d+)/$", views.Student8GenericAPIView.as_view()), ]
views视图文件
from django.shortcuts import render,HttpResponse from django.views import View from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status # Create your views here. class Student1View(View): def get(self,request): print(request.GET) print(type(request)) return HttpResponse("view1") class Student2APIView(APIView): def get(self,request): print(request.query_params) print(type(request)) return Response("view2",status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION,headers={"name":"alex"}) from students.models import Student from req.serializers import StudentModelSerializer class Student3APIView(APIView): def get(self, request): """获取所有数据""" student_list = Student.objects.all() # 序列化操作 serializer = StudentModelSerializer(instance=student_list, many=True) return Response(serializer.data) def post(self, request): # 获取用户提交的数据 data_dict = request.data # 实例化序列化器对象 serializer = StudentModelSerializer(data=data_dict) # 数据校验 serializer.is_valid(raise_exception=True) # 保存数据 serializer.save() return Response(serializer.validated_data) class Student4APIView(APIView): def get(self, request, pk): # 过滤pk对应的学生对象 student_obj = Student.objects.get(pk=pk) serializer = StudentModelSerializer(instance=student_obj) return Response(serializer.data) def put(self, request, pk): # 过滤pk对应的学生对象 student_obj = Student.objects.get(pk=pk) # 获取用户提交的数据 data_dict = request.data serializer = StudentModelSerializer(instance=student_obj, data=data_dict) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.validated_data) def delete(self, request, pk): Student.objects.filter(pk=pk).delete() return Response(status=status.HTTP_204_NO_CONTENT) from rest_framework.generics import GenericAPIView class Student5GenericAPIView(GenericAPIView): # 当前视图类中操作的公共数据,先从数据库查询出来 queryset = Student.objects.all() # 设置类视图中所有方法共有调用的序列化器类 serializer_class = StudentModelSerializer def get(self, request): # 获取模型数据 student_list = self.get_queryset() # 调用序列化器 serializer = self.get_serializer(instance=student_list, many=True) return Response(serializer.data) def post(self, request): """新增数据""" # 获取用户提交的数据并实例化序列化器对象 serializer = self.get_serializer(data=request.data) # 数据校验 serializer.is_valid(raise_exception=True) # 保存数据 serializer.save() return Response(serializer.data) class Student6GenericAPIView(GenericAPIView): # 当前视图类中操作的公共数据,先从数据库查询出来 queryset = Student.objects.all() # 设置类视图中所有方法共有调用的序列化器类 serializer_class = StudentModelSerializer def get(self, request, pk): """参数pk名,必须要叫pk,否则会报错。""" # 获取模型对象 instance = self.get_object() serializer = self.get_serializer(instance=instance) return Response(serializer.data) def put(self, request, pk): instance = self.get_object() serializer = self.get_serializer(instance=instance, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) def delete(self, request, pk): # 获取模型对象 instance = self.get_object() # 删除模型对象 instance.delete() return Response(status=status.HTTP_204_NO_CONTENT) from rest_framework.mixins import ListModelMixin, CreateModelMixin class Student7GenericAPIView(GenericAPIView, ListModelMixin, CreateModelMixin): queryset = Student.objects.all() serializer_class = StudentModelSerializer def get(self, request):
#获取所有数据 return self.list(request) def post(self, request):
#增加数据 return self.create(request) from rest_framework.mixins import RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin class Student8GenericAPIView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin): queryset = Student.objects.all() serializer_class = StudentModelSerializer def get(self, request, pk): return self.retrieve(request) def put(self, request, pk): return self.update(request) def delete(self, request, pk): return self.destroy(request)
使用POSTMAN调试
增加数据
数据库
修改数据
数据库
删除数据
2.5 内置的扩展子类
url路由文件
from django.urls import path,re_path from req import views urlpatterns = [ path('student1/',views.Student1View.as_view()), path('student2/', views.Student2APIView.as_view()), # 使用APIView path("student3/", views.Student3APIView.as_view()), re_path(r"^student3/(?P<pk>\d+)/$", views.Student4APIView.as_view()), # 使用GenericAPIView path("student4/", views.Student5GenericAPIView.as_view()), re_path(r"^student4/(?P<pk>\d+)/$", views.Student6GenericAPIView.as_view()), # 使用GenericAPIView,结合Mixin的扩展类 path("student5/", views.Student7GenericAPIView.as_view()), re_path(r"^student5/(?P<pk>\d+)/$", views.Student8GenericAPIView.as_view()), # 使用内置的扩展子类,生成API接口 path("student6/", views.Student9GenericAPIView.as_view()), re_path(r"^student6/(?P<pk>\d+)/$", views.Student10GenericAPIView.as_view()), ]
views视图文件
from django.shortcuts import render,HttpResponse from django.views import View from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status # Create your views here. class Student1View(View): def get(self,request): print(request.GET) print(type(request)) return HttpResponse("view1") class Student2APIView(APIView): def get(self,request): print(request.query_params) print(type(request)) return Response("view2",status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION,headers={"name":"alex"}) from students.models import Student from req.serializers import StudentModelSerializer class Student3APIView(APIView): def get(self, request): """获取所有数据""" student_list = Student.objects.all() # 序列化操作 serializer = StudentModelSerializer(instance=student_list, many=True) return Response(serializer.data) def post(self, request): # 获取用户提交的数据 data_dict = request.data # 实例化序列化器对象 serializer = StudentModelSerializer(data=data_dict) # 数据校验 serializer.is_valid(raise_exception=True) # 保存数据 serializer.save() return Response(serializer.validated_data) class Student4APIView(APIView): def get(self, request, pk): # 过滤pk对应的学生对象 student_obj = Student.objects.get(pk=pk) serializer = StudentModelSerializer(instance=student_obj) return Response(serializer.data) def put(self, request, pk): # 过滤pk对应的学生对象 student_obj = Student.objects.get(pk=pk) # 获取用户提交的数据 data_dict = request.data serializer = StudentModelSerializer(instance=student_obj, data=data_dict) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.validated_data) def delete(self, request, pk): Student.objects.filter(pk=pk).delete() return Response(status=status.HTTP_204_NO_CONTENT) from rest_framework.generics import GenericAPIView class Student5GenericAPIView(GenericAPIView): # 当前视图类中操作的公共数据,先从数据库查询出来 queryset = Student.objects.all() # 设置类视图中所有方法共有调用的序列化器类 serializer_class = StudentModelSerializer def get(self, request): # 获取模型数据 student_list = self.get_queryset() # 调用序列化器 serializer = self.get_serializer(instance=student_list, many=True) return Response(serializer.data) def post(self, request): """新增数据""" # 获取用户提交的数据并实例化序列化器对象 serializer = self.get_serializer(data=request.data) # 数据校验 serializer.is_valid(raise_exception=True) # 保存数据 serializer.save() return Response(serializer.data) class Student6GenericAPIView(GenericAPIView): # 当前视图类中操作的公共数据,先从数据库查询出来 queryset = Student.objects.all() # 设置类视图中所有方法共有调用的序列化器类 serializer_class = StudentModelSerializer def get(self, request, pk): """参数pk名,必须要叫pk,否则会报错。""" # 获取模型对象 instance = self.get_object() serializer = self.get_serializer(instance=instance) return Response(serializer.data) def put(self, request, pk): instance = self.get_object() serializer = self.get_serializer(instance=instance, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) def delete(self, request, pk): # 获取模型对象 instance = self.get_object() # 删除模型对象 instance.delete() return Response(status=status.HTTP_204_NO_CONTENT) from rest_framework.mixins import ListModelMixin, CreateModelMixin class Student7GenericAPIView(GenericAPIView, ListModelMixin, CreateModelMixin): queryset = Student.objects.all() serializer_class = StudentModelSerializer def get(self, request): return self.list(request) def post(self, request): return self.create(request) from rest_framework.mixins import RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin class Student8GenericAPIView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin): queryset = Student.objects.all() serializer_class = StudentModelSerializer def get(self, request, pk): return self.retrieve(request) def put(self, request, pk): return self.update(request) def delete(self, request, pk): return self.destroy(request) #DRF里面,内置了一些同时继承了GenericAPIView和Mixins扩展类的视图子类,我们可以直接继承这些子类就可以生成对应的API接口 #ListAPIView 获取所有数据 #CreateAPIView 添加数据 from rest_framework.generics import ListAPIView, CreateAPIView class Student9GenericAPIView(ListAPIView, CreateAPIView): queryset = Student.objects.all() serializer_class = StudentModelSerializer #RetrieveAPIView 获取一条数据 #UpdateAPIView 更新一条数据 #DestorAPIView 删除一条数据 #RetrieveUpdateDestoryAPIView 上面三个的缩写 from rest_framework.generics import RetrieveUpdateDestroyAPIView class Student10GenericAPIView(RetrieveUpdateDestroyAPIView): queryset = Student.objects.all() serializer_class = StudentModelSerializer
使用POSTMAN调试
可以使用相同的方式对其他方法进行调试
参考: