📅  最后修改于: 2023-12-03 15:30:28.945000             🧑  作者: Mango
perform_update()
is a method in Django Rest Framework (DRF) ViewSet that handles updating an object in the corresponding model. It is called when an HTTP PUT request is made to update an existing object.
def perform_update(self, serializer):
self
: The instance of the ViewSet.serializer
: The instance of the serializer class to update the object.The function does not return anything.
perform_update()
is called automatically when an HTTP PUT request is made to update an existing object. However, it can also be called manually.
class MyViewSet(viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MySerializer
def my_action(self, request, *args, **kwargs):
obj = self.get_object()
serializer = self.get_serializer(data=request.data, instance=obj)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
return Response(serializer.data)
In the above example, the my_action()
method calls perform_update()
to update an object using the data provided by the serializer.
## Django Rest Framework ViewSet perform_update
`perform_update()` is a method in Django Rest Framework (DRF) ViewSet that handles updating an object in the corresponding model. It is called when an HTTP PUT request is made to update an existing object.
### Signature
```python
def perform_update(self, serializer):
self
: The instance of the ViewSet.serializer
: The instance of the serializer class to update the object.The function does not return anything.
perform_update()
is called automatically when an HTTP PUT request is made to update an existing object. However, it can also be called manually.
class MyViewSet(viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MySerializer
def my_action(self, request, *args, **kwargs):
obj = self.get_object()
serializer = self.get_serializer(data=request.data, instance=obj)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
return Response(serializer.data)
In the above example, the my_action()
method calls perform_update()
to update an object using the data provided by the serializer.