当前位置: 移动技术网 > IT编程>脚本编程>Python > drf源码save以及response

drf源码save以及response

2019年09月06日  | 移动技术网IT编程  | 我要评论

tokyo hot n0461,天籁之爱歌谱,户县电视台

drf源码save以及response

一.save

其中蛮重要的一段

        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

其中的参数

#传入的参数
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

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

"""
返回值
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)

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网