部分更新通过Viewset Django Rest Framework失败

时间:2017-09-18 08:03:49

标签: python django django-rest-framework

每当通过api调用对象链接时,我想更新模型中的字段。我正在使用Django Rest Framework来处理api的创建。

指向单个对象的链接是

example.com/api/pk/ where pk is the object id.

在模型视图集中,我编写了一个部分更新方法,以便在调用对象时处理向字段添加1。

class RocNationViewSet(viewsets.ModelViewSet):
    queryset=RocNation.objects.filter(is_active=True).order_by('-pub_date')
    serializer_class=RocNationSerializer
    filter_backends = (DjangoFilterBackend,)


    def partial_update(self, request, pk=None):
        serializer=RocNationSerializer(rocnation, roc_views=F('roc_views')+1, partial=True)
        serializer.save()
        return Response(serializer.data)

该方法不执行操作。模型中的字段未更新。我错过了什么?

2 个答案:

答案 0 :(得分:1)

试一试:

@detail_route(methods=['POST','GET'])
def assign(self, request, pk):
    rocnation = self.get_object()
    data = {'roc_views': rocnation.roc_views + 1}
    serializer = RocNationSerializer(rocnation, data, partial=True)
    serializer.is_valid(raise_exception=True)
    serializer.save()
    return Response(serializer.data)

请访问example.com/api/1/assign

答案 1 :(得分:0)

这是为了使用Django API Rest更新部分字段所需要做的事情:

在你的django模块中:

#create API folder
mkdir api

然后添加__init__.py file

#create __init__.py__ file
touch __init__.py

现在您必须创建serializers.py文件:

from rest_framework import serializers 

from .models import "your model"
from .views *

class YourModelUpdateSerializer(serializers.ModelSerializer) :
    class Meta :
        model = "your model"
        fields = [
            #list of fields which could be updated
        ]

在API目录中创建一个view.py文件:

from rest_framework.generics import (
    CreateAPIView,
    UpdateAPIView,
    DestroyAPIView,
    ListAPIView, 
    RetrieveAPIView,
    )

from .models import "your model"

from .serializers import (
    YourModelUpdateSerializer,
    )

class YourModelUpdateAPIView(UpdateAPIView) :
    queryset = YourModel.objects.all()
    serializer_class = YourModelUpdateSerializer

最后,添加urls.py文件:

from django.conf.urls import url
from django.contrib import admin

from .views import (
    YourModelUpdateAPIView, 
    )

urlpatterns = [
    url(r'^(?P<pk>\d+)/edit/$', YourModelUpdateAPIView.as_view() , name="Update"),
    ]

它应该有效,因为它适用于我的项目;)

您有Django API REST文档here