如何在Django rest框架中执行UPDATE和DELETE操作

时间:2019-06-11 12:52:57

标签: python django django-rest-framework

我想在Django rest框架中执行UPDATE和DELETE操作,我执行了GET和POST操作。请帮助我进行UPDATE和DELETE操作。

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)),
]

1 个答案:

答案 0 :(得分:0)

ModelViewSet已经实现了PUT和DELETE HTTP方法的动作。

请参阅:https://www.django-rest-framework.org/api-guide/viewsets/#modelviewset

这意味着如果您执行HTTP请求:

删除/ api / settingprofile / 1

restframework 将调用 destroy(request,pk = 1)函数,以便从Setting_profile表中删除id = 1的行。

PUT / api / settingprofile / 2

restframework 将调用 update(request,pk = 2)函数并检查 request 参数,因此ID为2的行位于 Setting_profile 表将相应地更改为新数据。