Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 624
QuestionEverything Avatar asked Jun 01 '17 22:06

QuestionEverything


1 Answers

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')
like image 66
Ykh Avatar answered Oct 13 '22 22:10

Ykh