drf source save and response

Keywords: Python


One of the most important passages

        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.'
            self.instance = self.create(validated_data)
            assert self.instance is not None, (
                '`create()` did not return an object instance.'

        return self.instance

It's obvious here that save s our instance parameter because it determines whether it runs create or updata method in the future.

We can also customize the Create method and updata method without saving, because the essence of it is to call the create and updata methods.

Note: Our custom priority must be greater than the priority of the method that comes with drf, so it's appropriate for us to create these two methods in the model


The parameters

#Input parameters
def __init__(self, data=None, status=None,
                 template_name=None, headers=None,
                 exception=False, content_type=None):
#His assignment of parameters
        self.data = data
        self.template_name = template_name
        self.exception = exception
        self.content_type = content_type

We can modify the source code by inheriting classes

//Return value
    'status': 0,
    'msg': 'ok',
    'results': [],
    'token': ''
}, headers={}, status=200, content_type="")
//Let's say what we want.
APIResponse(0, 'ok', results,Other data)

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
        super().__init__(data=data, status=status, headers=headers, content_type=content_type)

Posted by dreamer on Tue, 08 Oct 2019 08:40:25 -0700