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!
The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .
The .is_valid() method takes an optional raise_exception flag that will cause it to raise a serializers.ValidationError exception if there are validation errors.
Django's serialization framework provides a mechanism for “translating” Django models into other formats. Usually these other formats will be text-based and used for sending Django data over a wire, but it's possible for a serializer to handle any format (text-based or not).
Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
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.
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.
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