Serializer.instance

Why do we have to do serializer.instance ? Isn’t serializer an instance that’s passed into the perform_update function ?

def perform_update(self, serializer):
serializer.instance.datecompleted = timezone.now()
serializer.save()

u’re right serializer is serializer instance which has 3 attributes: instance, data, context. what u want to save/change is instance of object - Todo. Serializer instance looks like below:

TodoCompleteSerializer(
    <Todo: Make coffe at 8 a.m.>,
    context={
           'request': <rest_framework.request.Request: PUT '/api/todos/2/complete/'>, 
           'format': None, 'view': <api.views.TodoComplete object>
    },
    data=<QueryDict: {}>, partial=False>): id = IntegerField(label='ID', read_only=True
)

type is: <class 'api.serializers.TodoCompleteSerializer'>. according to DRF docs:

When passing an initial object or queryset to a serializer instance, the object will be made available as .instance.

simillary u’ve got access to other attributes: serializer.data gives output: {'id': 2} and serializer.context:

{'request': <rest_framework.request.Request: PUT '/api/todos/2/complete/'>, 'format': None, 'view': <api.views.TodoComplete object at 0x7f5021bd4af0>}

so to have got acces to Todo object u need use .instance attribute. type of it (serializer.instance) is: <class 'todo.models.Todo'> . thx to that u can change something in the model and after save whole serializer.

Hope it’s clear :slight_smile: