Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some actions with object in UpdateAPIView when update

My code:

class CarView(generics.UpdateAPIView):
    permission_classes = (IsAdminUser,)
    serializer_class = CarSerializer

    def get_queryset(self):
        return ...

    def update(self, request, *args, **kwargs):
        # some actions
        return super(CarView, self).update(request, *args, **kwargs) 

In update method I want to do some operations with updated object. How to do this?

like image 922
Lev Avatar asked Jan 08 '23 08:01

Lev


2 Answers

You can get it with self.get_object()

Take a look at the source UpdateView, which you are overriding. You can use the same method to get the object:

class UpdateModelMixin(object):
    """
    Update a model instance.
    """
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        return Response(serializer.data)

    def perform_update(self, serializer):
        serializer.save()

    def partial_update(self, request, *args, **kwargs):
        kwargs['partial'] = True
        return self.update(request, *args, **kwargs)
like image 194
awwester Avatar answered Jan 15 '23 09:01

awwester


You can use the perform_update method which is available on views and is used to perform the update on the serializer. It is designed to be a hook that is triggered when the serializer needs to be saved (which performs the update), and it must call serializer.save() in order to do the update.

def perform_update(self, serializer):
    # get the object itself
    instance = self.get_object()
    # modify fields during the update
    modified_instance = serializer.save(model_field=new_value)

You can pass attributes that should be updated on the model in the save method on the serializer. It is not recommended to interact directly with the instance unless you are using the one returned from serializer.save(), which will contain any updated fields on the model.

like image 31
Kevin Brown-Silva Avatar answered Jan 15 '23 08:01

Kevin Brown-Silva