博客五部曲之三 - 博客RESTful


1270 浏览 5 years, 2 months

16 评论API

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

评论API

到目前为止,一些基本功能基本已完成,但是我们还是缺少一个评论模块
同样,在comments模块下面我们创建一个api库,然后依葫芦画瓢完成基本功能

comments.api.urls.py

urlpatterns = [
    url(r'^$', CommentListAPIView.as_view(), name="list"),    
    url(r'^(?P<id>\d+$)', CommentDetailAPIView.as_view(), name="thread"),    
    # url(r'^(?P<id>\d+)/delete$', comment_delete, name="delete"),   
]

comments.api.serializer.py

class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = [
            "id",
            "content_type",
            "object_id",
            "parent",
            "content"
        ]

comments.api.views.py

class CommentListAPIView(ListAPIView):
    serializer_class = CommentSerializer
    filter_backends = [SearchFilter, OrderingFilter]
    search_fields = ['content', 'user__first_name']
    pagination_class = PostLimitOffsetPagination
    def get_queryset(self, *args, **kwargs):
        # queryset_list = super(PostListAPIView, self).get_queryset(*args, **kwargs)
        queryset_list = Comment.objects.all()
        query = self.request.GET.get("q")
        if query:
            queryset_list = queryset_list.filter(
                Q(content__icontains=query) | 
                Q(user__first_name__icontains=query) |
                Q(user__last_name__icontains=query)
                ).distinct()
        return queryset_list

class CommentDetailAPIView(RetrieveAPIView):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer        

访问http://127.0.0.1:8000/api/comments/, 显示如下

从目前返回的RESTful信息里,看不到Post和Comments直接的关系,这个是接下来我们要做的