Overriding Djangorest ViewSets Delete Behavior
Asked Answered
S

1

9

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?

Schaffhausen answered 1/6, 2017 at 22:15 Comment(0)
N
22
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')
Nealon answered 2/6, 2017 at 0:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.