Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override serializer delete method in Django RF

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!

like image 619
Bryant James Avatar asked May 26 '17 20:05

Bryant James


People also ask

What is difference between serializer and ModelSerializer?

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 .

What is serializer Is_valid?

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.

What is serializing in Django?

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).

What is serializer and deserializer in Django?

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.


2 Answers

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.

like image 81
Mounir Avatar answered Sep 19 '22 18:09

Mounir


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.

like image 31
Rob Avatar answered Sep 18 '22 18:09

Rob