博客五部曲之三 - 博客RESTful


1551 浏览 5 years, 9 months

23 Update & Destroy Mixins 混入类

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

Update & Destroy Mixins

接下来我们会实现comments的操作,包括编辑和修改。
这一节我们使用的方式是mixin http://www.django-rest-framework.org/api-guide/generic-views/#mixins ,基于DetailView添加Mixin来实现相应的功能

基于DetailView基础,添加DestroyModelMixin和UpdateModelMixin,并添加put和delete方法来实现更新和删除。如果你是在UpdateAPIView里面添加RetrieveMixin,这儿需要添加get方法。

comments/api/views.py

from rest_framework.mixins import DestroyModelMixin, UpdateModelMixin

class CommentEditAPIView(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)

添加URL

comments/api/urls.py

    url(r'^(?P<pk>\d+)/edit/$', CommentEditAPIView.as_view(), name='edit'), #delete
]

访问 http://127.0.0.1:8000/api/comments/53/edit,可以看到Delete按钮和更新区域都出现了

前面的view中我们使用的还是Retrieve Serializer,接下来实现它自己的Serializer,去掉那些不想被编辑的field

comments/api/serializers.py

class CommentEditSerializer(ModelSerializer):
    class Meta:
        model = Comment
        fields = [
            'id',
            'content',
            'timestamp',
        ]

同时更新view里的Serializer

class CommentEditAPIView(DestroyModelMixin, UpdateModelMixin, RetrieveAPIView):

<span class="n">queryset</span> <span class="o">=</span> <span class="n">Comment</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">id__gte</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
serializer_class = CommentEditSerializer

再次刷新编辑页面,就会看到只有内容可以编辑了

如果执行删除操作,注意,跟admin后台删除一样,它会删除它的所有子评论,因为有ForeignKey关联

比如上面的53删除了,它的子评论54也会自动删除,下图可以看到他们的依赖关系