更新方法无效[DjangoRestFramework]

时间:2018-09-18 16:36:12

标签: django api django-rest-framework

我正在尝试通过使用Viewsets提取端点,由于某些原因,对其中一个端点的update()方法未保存更新的字段。

如何更新字段?

注意:我正在使用邮递员通过PUT方法进行测试

serializers.py:

class UpdateArticleSerializer(serializers.Serializer):

    title = serializers.CharField(max_length=250, required=True)
    body = serializers.CharField()
    image_url = serializers.URLField()
    keypoint = serializers.ListField()
    country = CountrySerializer(read_only=True)
    category = CategorySerializer(read_only=True)

    def create(self, validated_data):
        return Article(**validated_data)

    def update(self, instance, validated_data):
        instance.title = validated_data.get('title', instance.title)
        instance.body = validated_data.get('body', instance.body)
        instance.image_url = validated_data.get('image_url', 
            instance.image_url)
        instance.keypoint = validated_data.get('keypoint', 
            instance.keypoint)
        instance.country = validated_data.get('country', 
            instance.country)
        instance.category = validated_data.get('category', 
            instance.category)
        instance.save()

        return instance

views.py [更新方法]:

    def update(self, request, pk=None):
        article = Article.objects.get(id=pk)
        serializer = UpdateArticleSerializer(data=request.data)

        if article.author == request.user:
            if article.is_published != True:

                if serializer.is_valid():
                    serializer.save(author=request.user)
               queryset = article
               serializer = ArticleSerializer(queryset)   
                return 
                     Response(jsend.success({'post':serializer.data}), 
                     status=status.HTTP_200_OK)
            else: 
                return Response((jsend.error('Published post cannot be 
                  edited')), status=status.HTTP_409_CONFLICT)
        else:
            return Response((jsend.error("You are not authorized to 
            perform this action")), status=status.HTTP_403_FORBIDDEN)

1 个答案:

答案 0 :(得分:2)

serializer = UpdateArticleSerializer(data=request.data)

您没有提供现有实例,因此serializer.save()将被路由到serializer.create()

它应该类似于:

serializer = UpdateArticleSerializer(instance=self.get_object(), data=request.data)