在Django REST框架中,如何在使用ModeViewSet时允许部分更新?

我想为可以部分更新的对象创建REST API.在
http://www.django-rest-framework.org/api-guide/serializers/#partial-updates上给出了一个示例,其中在实例化序列化器时传递partial = True:

# Update `comment` with partial data
serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)

但是,在我的情况下,模型(称为SessionType)具有以下视图集:

class SessionTypeViewSet(viewsets.ModelViewSet):
    queryset = SessionType.objects.all()
    serializer_class = SessionTypeSerializer

序列化器定义为的位置

class SessionTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = SessionType
        fields = ('title',)

如何在此用例中调整序列化程序,以使partial始终为True?

最佳答案 您无需以任何方式调整序列化程序.使用该视图集,使用PATCH方法对“详细信息”端点的任何调用都将进行部分更新.

Django Rest Framework ModelViewSet基类包括以下mixin.在这里,您可以看到在调用partial_update时如何传递partial = True,默认情况下路由到PATCH方法:

class UpdateModelMixin(object):
    """
    Update a model instance.
    """
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # refresh the instance from the database.
            instance = self.get_object()
            serializer = self.get_serializer(instance)

        return Response(serializer.data)

    def perform_update(self, serializer):
        serializer.save()

    def partial_update(self, request, *args, **kwargs):
        kwargs['partial'] = True
        return self.update(request, *args, **kwargs)
点赞