博客五部曲之三 - 博客RESTful


1809 浏览 5 years, 2 months

23 Comment Detail, Update, & Delete

版权声明: 转载请注明出处 http://www.codingsoho.com/

Comment Detail, Update, & Delete

下一节我们会重构EditView,通常情况下我们会把它和DetailView结合起来,这两个的Serializer有太多重复的地方,差别主要是一些编辑field不同等。实现方法是使用同样的Serializer,但是设定一下readonlyfield

首先修改view,将原来的CommentEditAPIView改为CommentDetailAPIView (在这个基础上改动较小),同时更新serializer_class为CommentDetailSerializer

class CommentDetailAPIView(DestroyModelMixin, UpdateModelMixin, RetrieveAPIView):
    queryset = Comment.objects.filter(id__gte=0)
    serializer_class = CommentDetailSerializer
    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)
    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

修改CommentDetailSerializer,添加read_only_fields,这些field将不能被修改

class CommentDetailSerializer(serializers.ModelSerializer):
    class Meta:
        read_only_fields = [
            "content_type",
            "object_id",            
            "reply_count",
            "replies",
        ]

再次打开http://127.0.0.1:8000/api/comments/53,当前的DetailView同时支持Edit和Delete操作了。

即使你使用raw_data去修改read_only_fields,它也不会被接收。

对应的CommentEditSerializer,CommentEditAPIView都可以删除掉

对于comments的更新和删除,我们只允许它的作者去操作,所以需要加权限控制,如下

class CommentDetailAPIView(DestroyModelMixin, UpdateModelMixin, RetrieveAPIView):
    queryset = Comment.objects.filter(id__gte=0)
    serializer_class = CommentDetailSerializer
    permission_classes = [IsAuthenticatedOrReadOnly, IsOwnerReadonly]

加完之后,非授权用户只能查看,没有更新和删除接口。但是授权用户也不能看到删除按钮了?

原因是IsOwnerReadonly里面做了限制,去掉has_permission这个,我们不再需要

class IsOwnerReadonly(BasePermission):
    message = "you must be the owener of this object"
    # my_safe_method = ["PUT","GET"]
    #
    # def has_permission(self, request, view):
    #     if request.method in self.my_safe_method:
    #         return True
    #     return False

再次刷新网页,删除按钮回来了。 一起回来的还有OPTIONS。

# ('GET', 'HEAD', 'OPTIONS') 是三个默认的SAFE METHOD,定义在宏 SAFE_METHODS