一 关于视图类的一下概念
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对象的数据是自动根据前端发送数据的格式进行解析之后的结果。
无论前端发送的哪种格式的数据,我们都可以以统一的方式读取数据。
常用属性:
1. data
request.data 返回解析之后的请求体数据。类似于Django中标准的 request.POST 和 request.FILES 属性,但提供如下特性:
包含了解析之后的文件和非文件数据
包含了对POST、PUT、PATCH请求方式解析后的数据
利用了REST framework的parsers解析器,不仅支持表单类型数据,也支持JSON数据
2. query_params
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会根据前端所需类型数据来设置该参数。
常用属性(用的不多):
1. data:传给response对象的序列化后,但尚未render处理的数据
2. status_code:状态码的数字
3. content:经过render处理后的响应数据
为了方便设置状态码, REST Framework在rest_framework.status模块中提供了常用状态码常量。
1.3 状态码信息
信息告知---1XX
成功---2XX
重定向---3XX
客户端错误---4XX
服务器错误---5XX
二 视图
REST framework 提供了众多的通用视图基类与扩展类,以简化视图的编写。
2.1 APIView和View区别
Django REST framwork 提供的视图的主要作用:
控制序列化器的执行(检验、保存、转换数据)
控制数据库查询的执行
APIView
from rest_framework.viewsimport APIView
是REST framework提供的所有视图的基类,继承自Django的View父类。
APIView 与View的不同之处在于:
传入到视图方法中的是REST framework的request对象,而不是Django的HttpRequest对象;
视图方法可以返回REST framework的Response对象,视图会为响应数据设置(render)符合前端要求的格式;
任何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 importadminfrom django.urls importpath,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 importpath,re_pathfrom req importviews
urlpatterns=[
path('student1/',views.Student1View.as_view()),
path('student2/', views.Student2APIView.as_view()),
]
视图文件
from django.shortcuts importrender,HttpResponsefrom django.views importView#Create your views here.
classStudent1View(View):defget(self,request):print(request)print(type(request))return HttpResponse("view1")classStudent2APIView(View):defget(self,request):print(request)print(type(request))return HttpResponse("view2")
访问对比
http://127.0.0.1:8000/req/student1/
打印结果
http://127.0.0.1:8000/req/student2/
打印结果
加参数访问,提取参数结果
from django.shortcuts importrender,HttpResponsefrom django.views importViewfrom rest_framework.views importAPIView#Create your views here.
classStudent1View(View):defget(self,request):print(request.GET)print(type(request))return HttpResponse("view1")classStudent2APIView(APIView):defget(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
打印结果
[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
使用responbe定义状态码响应
from django.shortcuts importrender,HttpResponsefrom django.views importViewfrom rest_framework.views importAPIViewfrom rest_framework.response importResponsefrom rest_framework importstatus#Create your views here.
classStudent1View(View):defget(self,request):print(request.GET)print(type(request))return HttpResponse("view1")classStudent2APIView(APIView):defget(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 importrender,HttpResponsefrom django.views importViewfrom rest_framework.views importAPIViewfrom rest_framework.response importResponsefrom rest_framework importstatus#Create your views here.
classStudent1View(View):defget(self,request):print(request.GET)print(type(request))return HttpResponse("view1")classStudent2APIView(APIView):defget(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\d+) #获取一条数据
PUT /req/student3/(?P\d+) #更新一条数据
DELETE /req/student3/(?P\d+) #删除一条数据
url路由配置
from django.urls importpath,re_pathfrom req importviews
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\d+)/$", views.Student4APIView.as_view()),
]
新建serializer文件,序列操作
(drfdemo) root@darren-virtual-machine:~/PycharmProjects/drfdemo/drf_demo# vim req/serializers.py
from students.models importStudentfrom rest_framework importserializersclassStudentModelSerializer(serializers.ModelSerializer):classMeta:
model=Student
fields= ["id", "name", "age", "sex"]
extra_kwargs={"name": {"max_length": 10, "min_length": 4},"age": {"max_value": 150, "min_value": 0},
}defvalidate_name(self, data):if data == "root":raise serializers.ValidationError("用户名不能为root!")returndatadefvalidate(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 importrender,HttpResponsefrom django.views importViewfrom rest_framework.views importAPIViewfrom rest_framework.response importResponsefrom rest_framework importstatus#Create your views here.
classStudent1View(View):defget(self,request):print(request.GET)print(type(request))return HttpResponse("view1")classStudent2APIView(APIView):defget(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 importStudentfrom req.serializers importStudentModelSerializerclassStudent3APIView(APIView):defget(self, request):"""获取所有数据"""student_list=Student.objects.all()#序列化操作
serializer = StudentModelSerializer(instance=student_list, many=True)returnResponse(serializer.data)defpost(self, request):#获取用户提交的数据
data_dict =request.data#实例化序列化器对象
serializer = StudentModelSerializer(data=data_dict)#数据校验
serializer.is_valid(raise_exception=True)#保存数据
serializer.save()returnResponse(serializer.validated_data)classStudent4APIView(APIView):defget(self, request, pk):#过滤pk对应的学生对象
student_obj = Student.objects.get(pk=pk)
serializer= StudentModelSerializer(instance=student_obj)returnResponse(serializer.data)defput(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()returnResponse(serializer.validated_data)defdelete(self, request, pk):
Student.objects.filter(pk=pk).delete()return Response(status=status.HTTP_204_NO_CONTENT)
使用POSTMAN调试
获取所有
添加数据
查看数据库
修改数据
查看数据库
删除
数据库查看
状态码
2.2 GenericAPIView(通用视图类)
from rest_framework.genericsimport GenericAPIView
继承自APIView,主要增加了操作序列化器和数据库查询的方法,作用是为下面Mixin扩展类的执行提供方法支持。通常在使用时,可搭配一个或多个Mixin扩展类。
提供的关于序列化器使用的属性与方法
属性:serializer_class 指明视图使用的序列化器
方法:get_serializer_class(self)
当出现一个视图类中调用多个序列化器时,那么可以通过条件判断在get_serializer_class方法中通过返回不同的序列化器类名就可以让视图方法执行不同的序列化器对象了。
返回序列化器类,默认返回serializer_class,可以重写,例如:
defget_serializer_class(self):
ifself.request.user.is_staff:
returnFullAccountSerializer
return BasicAccountSerializer
get_serializer(self, args, *kwargs)
返回序列化器对象,主要用来提供给Mixin扩展类使用,如果我们在视图中想要获取序列化器对象,也可以直接调用此方法。
提供的关于数据库查询的属性与方法
属性:queryset 指明使用的数据查询集
方法:get_queryset(self)
返回视图使用的查询集,主要用来提供给Mixin扩展类使用,是列表视图与详情视图获取数据的基础,默认返回queryset属性,可以重写,例如:
defget_queryset(self):
user =self.request.user
return user.accounts.all()
get_object(self)
返回详情视图所需的模型类数据对象,主要用来提供给Mixin扩展类使用。
在试图中可以调用该方法获取详情信息的模型类对象。
其他可以设置的属性
pagination_class 指明分页控制类
filter_backends 指明过滤控制后端
2.3 GenericAPIView实现接口
url路由
from django.urls importpath,re_pathfrom req importviews
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\d+)/$", views.Student4APIView.as_view()),#使用GenericAPIView
path("student4/", views.Student5GenericAPIView.as_view()),
re_path(r"^student4/(?P\d+)/$", views.Student6GenericAPIView.as_view()),
]
实现5个功能
使用GenericAPIView提供学生信息的5个API接口
GET/req/student4/ #获取全部数据
POST /req/student4/ #添加数据
GET/req/student4/(?P\d+) #获取一条数据
PUT /req/student4/(?P\d+) #更新一条数据
DELETE /req/student4/(?P\d+) #删除一条数据
视图文件
from django.shortcuts importrender,HttpResponsefrom django.views importViewfrom rest_framework.views importAPIViewfrom rest_framework.response importResponsefrom rest_framework importstatus#Create your views here.
classStudent1View(View):defget(self,request):print(request.GET)print(type(request))return HttpResponse("view1")classStudent2APIView(APIView):defget(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 importStudentfrom req.serializers importStudentModelSerializerclassStudent3APIView(APIView):defget(self, request):"""获取所有数据"""student_list=Student.objects.all()#序列化操作
serializer = StudentModelSerializer(instance=student_list, many=True)returnResponse(serializer.data)defpost(self, request):#获取用户提交的数据
data_dict =request.data#实例化序列化器对象
serializer = StudentModelSerializer(data=data_dict)#数据校验
serializer.is_valid(raise_exception=True)#保存数据
serializer.save()returnResponse(serializer.validated_data)classStudent4APIView(APIView):defget(self, request, pk):#过滤pk对应的学生对象
student_obj = Student.objects.get(pk=pk)
serializer= StudentModelSerializer(instance=student_obj)returnResponse(serializer.data)defput(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()returnResponse(serializer.validated_data)defdelete(self, request, pk):
Student.objects.filter(pk=pk).delete()return Response(status=status.HTTP_204_NO_CONTENT)from rest_framework.generics importGenericAPIViewclassStudent5GenericAPIView(GenericAPIView):#当前视图类中操作的公共数据,先从数据库查询出来
queryset =Student.objects.all()#设置类视图中所有方法共有调用的序列化器类
serializer_class =StudentModelSerializerdefget(self, request):#获取模型数据
student_list =self.get_queryset()#调用序列化器
serializer = self.get_serializer(instance=student_list, many=True)returnResponse(serializer.data)defpost(self, request):"""新增数据"""
#获取用户提交的数据并实例化序列化器对象
serializer = self.get_serializer(data=request.data)#数据校验
serializer.is_valid(raise_exception=True)#保存数据
serializer.save()returnResponse(serializer.data)classStudent6GenericAPIView(GenericAPIView):#当前视图类中操作的公共数据,先从数据库查询出来
queryset =Student.objects.all()#设置类视图中所有方法共有调用的序列化器类
serializer_class =StudentModelSerializerdefget(self, request, pk):"""参数pk名,必须要叫pk,否则会报错。"""
#获取模型对象
instance =self.get_object()
serializer= self.get_serializer(instance=instance)returnResponse(serializer.data)defput(self, request, pk):
instance=self.get_object()
serializer= self.get_serializer(instance=instance, data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()returnResponse(serializer.data)defdelete(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 importpath,re_pathfrom req importviews
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\d+)/$", views.Student4APIView.as_view()),#使用GenericAPIView
path("student4/", views.Student5GenericAPIView.as_view()),
re_path(r"^student4/(?P\d+)/$", views.Student6GenericAPIView.as_view()),#使用GenericAPIView,结合Mixin的扩展类
path("student5/", views.Student7GenericAPIView.as_view()),
re_path(r"^student5/(?P\d+)/$", views.Student8GenericAPIView.as_view()),
]
views视图文件
from django.shortcuts importrender,HttpResponsefrom django.views importViewfrom rest_framework.views importAPIViewfrom rest_framework.response importResponsefrom rest_framework importstatus#Create your views here.
classStudent1View(View):defget(self,request):print(request.GET)print(type(request))return HttpResponse("view1")classStudent2APIView(APIView):defget(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 importStudentfrom req.serializers importStudentModelSerializerclassStudent3APIView(APIView):defget(self, request):"""获取所有数据"""student_list=Student.objects.all()#序列化操作
serializer = StudentModelSerializer(instance=student_list, many=True)returnResponse(serializer.data)defpost(self, request):#获取用户提交的数据
data_dict =request.data#实例化序列化器对象
serializer = StudentModelSerializer(data=data_dict)#数据校验
serializer.is_valid(raise_exception=True)#保存数据
serializer.save()returnResponse(serializer.validated_data)classStudent4APIView(APIView):defget(self, request, pk):#过滤pk对应的学生对象
student_obj = Student.objects.get(pk=pk)
serializer= StudentModelSerializer(instance=student_obj)returnResponse(serializer.data)defput(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()returnResponse(serializer.validated_data)defdelete(self, request, pk):
Student.objects.filter(pk=pk).delete()return Response(status=status.HTTP_204_NO_CONTENT)from rest_framework.generics importGenericAPIViewclassStudent5GenericAPIView(GenericAPIView):#当前视图类中操作的公共数据,先从数据库查询出来
queryset =Student.objects.all()#设置类视图中所有方法共有调用的序列化器类
serializer_class =StudentModelSerializerdefget(self, request):#获取模型数据
student_list =self.get_queryset()#调用序列化器
serializer = self.get_serializer(instance=student_list, many=True)returnResponse(serializer.data)defpost(self, request):"""新增数据"""
#获取用户提交的数据并实例化序列化器对象
serializer = self.get_serializer(data=request.data)#数据校验
serializer.is_valid(raise_exception=True)#保存数据
serializer.save()returnResponse(serializer.data)classStudent6GenericAPIView(GenericAPIView):#当前视图类中操作的公共数据,先从数据库查询出来
queryset =Student.objects.all()#设置类视图中所有方法共有调用的序列化器类
serializer_class =StudentModelSerializerdefget(self, request, pk):"""参数pk名,必须要叫pk,否则会报错。"""
#获取模型对象
instance =self.get_object()
serializer= self.get_serializer(instance=instance)returnResponse(serializer.data)defput(self, request, pk):
instance=self.get_object()
serializer= self.get_serializer(instance=instance, data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()returnResponse(serializer.data)defdelete(self, request, pk):#获取模型对象
instance =self.get_object()#删除模型对象
instance.delete()return Response(status=status.HTTP_204_NO_CONTENT)from rest_framework.mixins importListModelMixin, CreateModelMixinclassStudent7GenericAPIView(GenericAPIView, ListModelMixin, CreateModelMixin):
queryset=Student.objects.all()
serializer_class=StudentModelSerializerdefget(self, request):
#获取所有数据returnself.list(request)defpost(self, request):
#增加数据returnself.create(request)from rest_framework.mixins importRetrieveModelMixin, UpdateModelMixin, DestroyModelMixinclassStudent8GenericAPIView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
queryset=Student.objects.all()
serializer_class=StudentModelSerializerdefget(self, request, pk):returnself.retrieve(request)defput(self, request, pk):returnself.update(request)defdelete(self, request, pk):return self.destroy(request)
使用POSTMAN调试
增加数据
数据库
修改数据
数据库
删除数据
2.5 内置的扩展子类
url路由文件
from django.urls importpath,re_pathfrom req importviews
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\d+)/$", views.Student4APIView.as_view()),#使用GenericAPIView
path("student4/", views.Student5GenericAPIView.as_view()),
re_path(r"^student4/(?P\d+)/$", views.Student6GenericAPIView.as_view()),#使用GenericAPIView,结合Mixin的扩展类
path("student5/", views.Student7GenericAPIView.as_view()),
re_path(r"^student5/(?P\d+)/$", views.Student8GenericAPIView.as_view()),#使用内置的扩展子类,生成API接口
path("student6/", views.Student9GenericAPIView.as_view()),
re_path(r"^student6/(?P\d+)/$", views.Student10GenericAPIView.as_view()),
]
views视图文件
from django.shortcuts importrender,HttpResponsefrom django.views importViewfrom rest_framework.views importAPIViewfrom rest_framework.response importResponsefrom rest_framework importstatus#Create your views here.
classStudent1View(View):defget(self,request):print(request.GET)print(type(request))return HttpResponse("view1")classStudent2APIView(APIView):defget(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 importStudentfrom req.serializers importStudentModelSerializerclassStudent3APIView(APIView):defget(self, request):"""获取所有数据"""student_list=Student.objects.all()#序列化操作
serializer = StudentModelSerializer(instance=student_list, many=True)returnResponse(serializer.data)defpost(self, request):#获取用户提交的数据
data_dict =request.data#实例化序列化器对象
serializer = StudentModelSerializer(data=data_dict)#数据校验
serializer.is_valid(raise_exception=True)#保存数据
serializer.save()returnResponse(serializer.validated_data)classStudent4APIView(APIView):defget(self, request, pk):#过滤pk对应的学生对象
student_obj = Student.objects.get(pk=pk)
serializer= StudentModelSerializer(instance=student_obj)returnResponse(serializer.data)defput(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()returnResponse(serializer.validated_data)defdelete(self, request, pk):
Student.objects.filter(pk=pk).delete()return Response(status=status.HTTP_204_NO_CONTENT)from rest_framework.generics importGenericAPIViewclassStudent5GenericAPIView(GenericAPIView):#当前视图类中操作的公共数据,先从数据库查询出来
queryset =Student.objects.all()#设置类视图中所有方法共有调用的序列化器类
serializer_class =StudentModelSerializerdefget(self, request):#获取模型数据
student_list =self.get_queryset()#调用序列化器
serializer = self.get_serializer(instance=student_list, many=True)returnResponse(serializer.data)defpost(self, request):"""新增数据"""
#获取用户提交的数据并实例化序列化器对象
serializer = self.get_serializer(data=request.data)#数据校验
serializer.is_valid(raise_exception=True)#保存数据
serializer.save()returnResponse(serializer.data)classStudent6GenericAPIView(GenericAPIView):#当前视图类中操作的公共数据,先从数据库查询出来
queryset =Student.objects.all()#设置类视图中所有方法共有调用的序列化器类
serializer_class =StudentModelSerializerdefget(self, request, pk):"""参数pk名,必须要叫pk,否则会报错。"""
#获取模型对象
instance =self.get_object()
serializer= self.get_serializer(instance=instance)returnResponse(serializer.data)defput(self, request, pk):
instance=self.get_object()
serializer= self.get_serializer(instance=instance, data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()returnResponse(serializer.data)defdelete(self, request, pk):#获取模型对象
instance =self.get_object()#删除模型对象
instance.delete()return Response(status=status.HTTP_204_NO_CONTENT)from rest_framework.mixins importListModelMixin, CreateModelMixinclassStudent7GenericAPIView(GenericAPIView, ListModelMixin, CreateModelMixin):
queryset=Student.objects.all()
serializer_class=StudentModelSerializerdefget(self, request):returnself.list(request)defpost(self, request):returnself.create(request)from rest_framework.mixins importRetrieveModelMixin, UpdateModelMixin, DestroyModelMixinclassStudent8GenericAPIView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
queryset=Student.objects.all()
serializer_class=StudentModelSerializerdefget(self, request, pk):returnself.retrieve(request)defput(self, request, pk):returnself.update(request)defdelete(self, request, pk):returnself.destroy(request)#DRF里面,内置了一些同时继承了GenericAPIView和Mixins扩展类的视图子类,我们可以直接继承这些子类就可以生成对应的API接口#ListAPIView 获取所有数据#CreateAPIView 添加数据
from rest_framework.generics importListAPIView, CreateAPIViewclassStudent9GenericAPIView(ListAPIView, CreateAPIView):
queryset=Student.objects.all()
serializer_class=StudentModelSerializer#RetrieveAPIView 获取一条数据#UpdateAPIView 更新一条数据#DestorAPIView 删除一条数据#RetrieveUpdateDestoryAPIView 上面三个的缩写
from rest_framework.generics importRetrieveUpdateDestroyAPIViewclassStudent10GenericAPIView(RetrieveUpdateDestroyAPIView):
queryset=Student.objects.all()
serializer_class= StudentModelSerializer
使用POSTMAN调试
可以使用相同的方式对其他方法进行调试
参考: