博客五部曲之三 - 博客RESTful


1479 浏览 5 years, 9 months

18 在Post详情视图里添加评论

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

在Post详情视图里添加评论

上一节我们在评论的详情里添加了它的子评论。我们可以用同样的方法在Post详情视图里添加它的评论信息。

修改PostDetailSerializer,添加序列化方法字段 comments,在get_comments函数里,获取当前对象关联的这些评论对象,然后会用CommentSerializer去序列化它

class PostDetailSerializer(serializers.ModelSerializer):
    url = post_detail_url
    user = SerializerMethodField()
    image = SerializerMethodField()
    html = SerializerMethodField()
    comments = SerializerMethodField()
    class Meta:
        model = Post
        fields = [
            "url",
            "title",
            "slug",
            "publish",
            "user",
            "image",
            "content",
            "html",
            "comments"
        ]
    def get_comments(self, obj):
          c_qs = Comment.objects.filter_by_instance(obj)
          comments = CommentSerializer(c_qs, many=True).data
          return comments

test帖子下面有两个评论,访问 http://127.0.0.1:8000/api/posts/test/,可以看到帖子详情视图下面显示出了它的两个评论

GET /api/posts/test/
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
    "url": "[http://127.0.0.1](http://127.0.0.1):8000/api/posts/test/",
    "title": "test",
    "slug": "test",
    "publish": "2018-04-18",
    "user": "bhe001",
    "image": "/media/None/085825680.jpg",
    "content": "test",
    "html": "<p>test</p>\n",
    "comments": [
        {
            "id": 48,
            "content_type": 7,
            "object_id": 5,
            "parent": null,
            "content": "comments 2 on test",
            "reply_count": 2
        },
        {
            "id": 47,
            "content_type": 7,
            "object_id": 5,
            "parent": null,
            "content": "comments on test",
            "reply_count": 0
        }
    ]
}