问题
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!
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/44209878/override-serializer-delete-method-in-django-rf