前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >drf源码save以及response

drf源码save以及response

作者头像
小小咸鱼YwY
发布2019-09-11 15:11:42
3230
发布2019-09-11 15:11:42
举报
文章被收录于专栏:python-爬虫python-爬虫

drf源码save以及response

一.save

其中蛮重要的一段

代码语言:javascript
复制
        if self.instance is not None:
            self.instance = self.update(self.instance, validated_data)
            assert self.instance is not None, (
                '`update()` did not return an object instance.'
            )
        else:
            self.instance = self.create(validated_data)
            assert self.instance is not None, (
                '`create()` did not return an object instance.'
            )

        return self.instance

这里呢很明显就可以看出save我们传参instance的由于决定了他后续是运行create还是updata方法

我们也可以不用save,可以自定义create 方法和updata方法因为他本质就是调用create和updata方法

注意点:我们自定义优先级必须大于drf自带的方法的优先级,所有我们把这两个方法创建在模型中比较合适

二.response

其中的参数

代码语言:javascript
复制
#传入的参数
def __init__(self, data=None, status=None,
                 template_name=None, headers=None,
                 exception=False, content_type=None):
    
#他对于参数进行的赋值
        self.data = data
        self.template_name = template_name
        self.exception = exception
        self.content_type = content_type

我们可以通过类的继承来修改源码

代码语言:javascript
复制
"""
返回值
Response({
    'status': 0,
    'msg': 'ok',
    'results': [],
    'token': ''
}, headers={}, status=200, content_type="")
"""
'''
比如说我们想要的效果
APIResponse(0, 'ok', results,其他数据)
'''

from rest_framework.response import Response
class APIResponse(Response):
    def __init__(self, data_status, data_msg, results=None,
                 status=None, headers=None, content_type=None, **kwargs):
        data = {
            'status': data_status,
            'msg': data_msg
        }
        if results is not None:
            data['results'] = results
        data.update(kwargs)
        super().__init__(data=data, status=status, headers=headers, content_type=content_type)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • drf源码save以及response
    • 一.save
      • 二.response
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档