How to perform UPDATE and DELETE operation in Django rest framework

Question:

I want to perform UPDATE and DELETE operation in Django rest framework, I did GET and POST operation. Please help me to do UPDATE and DELETE operation.

views.py

class SettingprofileViews(viewsets.ModelViewSet):
    queryset = Setting_profile.objects.all()
    serializer_class = SettingprofileSerializer

models.py

class Setting_profile(models.Model):
    name = models.CharField(max_length=255, blank=True, null=True)
    contact_number = models.CharField(max_length=12, blank=True, null=True)
    email = models.EmailField(max_length=100, blank=True, null=True)
    address = models.CharField(max_length=500, blank=True, null=True)

serializers.py

class SettingprofileSerializer(serializers.ModelSerializer):

    class Meta:
        model = Setting_profile
        fields = '__all__'

urls.py

router = routers.DefaultRouter()
router.register('api/settingprofile', views.SettingprofileViews)

urlpatterns = [
    path('', include(router.urls)),
]
Asked By: Kumar

||

Answers:

The ModelViewSet already implements actions for PUT and DELETE HTTP methods.

See: https://www.django-rest-framework.org/api-guide/viewsets/#modelviewset

It means that if you perform HTTP requests:

DELETE /api/settingprofile/1

The restframework will call destroy(request, pk=1) function in order to remove row with id=1 from Setting_profile table.

PUT /api/settingprofile/2

The restframework will call update(request, pk=2) function and inspect request parameter, so the row with id=2 in Setting_profile table will be changed accordingly to a new data.

Answered By: Jeho