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?
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With