Search code examples
pythondjangodjango-rest-frameworksql-deletedjango-rest-viewsets

Overriding Djangorest ViewSets Delete Behavior


I have defined a Model like this:

class Doctor(models.Model):
    name = models.CharField(max_length=100)
    is_active = models.BooleanField(default=True)

My Serializer:

class DoctorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Doctor
        fields = ('id', 'name', )

In View:

class DoctorViewSet(viewsets.ModelViewSet):
    queryset = Doctor.objects.all()
    serializer_class = DoctorSerializer

Now, I can delete a doctor by calling the url: 'servername/doctors/id/', with the http method DELETE. However, I want to override the delete behavior for this model. I want that, when the user deletes a record, it's is_active field is set to false, without actually deleting the record from the database. I also want to keep the other behaviors of Viewset like the list, put, create as they are.

How do I do that? Where do I write the code for overriding this delete behavior?


Solution

  • class DoctorViewSet(viewsets.ModelViewSet):
        queryset = Doctor.objects.all()
        serializer_class = DoctorSerializer
    
        def destroy(self, request, *args, **kwargs):
            doctor = self.get_object()
            doctor.is_active = False
            doctor.save()
            return Response(data='delete success')