Reputation: 1694
I have a serializer that inherits from the django rest framework serializer ModelSerializer
.
To overwrite the create method, I can redefine create
. To redefine the update method, I redefine update
. I'm looking through the code though and can't find the method to overwrite for deletion. I need to do this in the serializer so I can grab the deleting user.
Any thoughts would be appreciated!
Upvotes: 14
Views: 23481
Reputation: 11726
I think you can do that but in the view level.
So if you're using ModelViewsets you can override the destory method or the perform_destroy
and add your business logic.
def perform_destroy(self, instance):
# custom code, pre deletion
super().perform_destroy(instance)
# custom code, post deletion
https://www.cdrf.co/3.3/rest_framework.mixins/DestroyModelMixin.html
Upvotes: 13
Reputation: 877
If you're using a ModelViewSet, you could do it in the view:
class YourViewSetClass(ModelViewSet):
def destroy(self, request, *args, **kwargs):
user = request.user # deleting user
# you custom logic #
return super(YourViewSetClass, self).destroy(request, *args, **kwargs)
The destroy method is so simple (just a call to instance.delete()) that the action is not delegated to the serializer. The serializers in DRF are for negotiating external representations to/from your database models. Here you simply want to delete a model.
Upvotes: 23