Override serializer delete method in Django RF

妖精的绣舞 提交于 2020-06-27 07:34:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!