第三章 DRF之View进化论

Django+View+json [弃]
无法序列化日期类型

path('study/grades', GradeListView.as_view()),
json.dumps()函数是将一个Python数据类型列表进行json格式的编码(可以这么理解,json.dumps()函数是将字典转化为字符串)
json.loads()函数是将json格式数据转换为字典(可以这么理解,json.loads()函数是将字符串转化为字典)

Django+View+model_to_dict[弃]
无法序列化图片格式,默认的不可修改的日期也不会被序列化,可修改的日期可以被序列化


Django+View+serializer


Django+View+JsonResponse
JsonResponse 接收的参数可以直接是字典类型的,这里的serializer会自动生成字符串类型的,因此需要将字符串再次转为字典才能给JsonResponse使用。这里只是演示。实际用HttpReponse更好。


返回的json_data

DRF+APIView+Serializer+Response
前面四种View都是Django自带的,从APIView开始都是 DRF的


Get方法返回的是Response,里面接受的参数是serializer.data

做个实验:
A把上面一节的JsonResponse替换成DRF的Response结果是错误的

B假如把这个Response替换成JsonResponce 结果还是可以用的


对于Response的官方解释:
REST framework 通过提供一个Response 类来支持 HTTP content negotiation,该类允许你返回可以呈现为多种内容类型的内容,具体取决于客户端的请求。
Response 类是 Django中SimpleTemplateResponse(继承了HttpResponse)类的一个子类。Response 对象用Python基本数据类型初始化。然后REST framework 使用标准的HTTP content negotiation 来确定如何呈现最终的响应内容。
你并不需要一定是用 Response 类,你可以从你的视图返回常规的 HttpResponse 或者 StreamingHttpResponse 对象。使用Response类只提供了一个可以呈现多种格式的更好的界面来返回 content-negotiated 的 Web API 响应。
除非由于某种原因你要对 REST
framework 做大量的自定义,否则你应该始终对返回对象的views使用 APIView 类或者 @api_view 函数。这样做可以确保视图在返回之前能够执行 content negotiation 并且为响应选择适当的渲染器
新建Grade


DRF+APIView+GetDetail/Update/Delete
上一节实现了对资源的列表查询以及创建
这一节补充剩下的3种操作获取单个资源详细信息、更新、删除





点击删除按钮,即可删除
DRF+GenericAPIView+mixins
Mixins里面提供了很多类,ListModelMixin提供了list方法。
GenericAPIView则提供了queryset属性以及序列化、分页类的指定


DRF+GenericAPIView子类实现增删改查
和APIView相比,基本不用怎么写代码,只是简单的写两行






DRF+ViewSet
ViewSet 继承自 APIView。你可以使用任何标准属性,如 permission_classes, authentication_classes 以便控制视图集上的 API策略。
ViewSet 类不提供任何操作的实现。为了使用ViewSet 类,你将重写该类并显式地定义动作实现。
ViewSet提供了路由router绑定的方式,并且将get put
post 等映射为retrieve update create
其配置方式为:

http://127.0.0.1:8000/study/grades0/
http://127.0.0.1:8000/study/grades0/1/
但是好像不支持自动分页


DRF+GenericViewSet+Mixins
GenericViewSet 类继承自GenericAPIView,并提供了 get_object, get_queryset 方法和其他通用视图基本行为的默认配置,但默认情况不包括任何操作。



总结
其种 GenericAPIView/GenericViewSet提供了Patch方法,ViewSet可以自己写patch方法
实际项目种尽量使用GenericViewSet+mixins 或者直接使用ModelViewSet
ViewSet/GenericViewSet 重写了as_view 方法,将HTTP的请求动作绑定到了具体的方法:
GET grades/ list
GET grades/1/ retrieve
POST grades/ create
PUT grades/1/ update
PATCH grades/1/ partial_update
DELETE grades/1/ destroy
