博客五部曲之三 - 博客RESTful
1419 浏览 5 years, 9 months
24 Comment URLs & Post Get API URLs
版权声明: 转载请注明出处 http://www.codingsoho.com/Comment URLs & Post Get API URLs
在ListView里面,字段大多以数字形式显示,这一节我们会让这些内容更直接一些,显示为有意义的值或者超链接到具体对象。
修改方法跟post类似
首先在ListView里添加到DetailView的超链接
添加url为HyperlinkedIdentityField,并将这个url添加到fields。
注释掉三个field,这些我们可以在DetailView直接查看
class CommentListSerializer(serializers.ModelSerializer):
url = HyperlinkedIdentityField(view_name='comments-api:thread')
class Meta:
model = Comment
fields = [
"url",
"id",
# "content_type",
# "object_id",
# "parent",
"content",
"reply_count"
]
在DetailView里面,显示post的具体的路径。方法是通过SerializerMethodField
。
同样注释掉content_type和content_id,这个可以反映在content_object_url里。
class CommentDetailSerializer(serializers.ModelSerializer):
reply_count = SerializerMethodField()
content_object_url = SerializerMethodField()
replies = SerializerMethodField()
class Meta:
model = Comment
fields = [
"id",
# "content_type",
# "object_id",
"content",
"reply_count",
"replies",
"timestamp",
"content_object_url"
]
read_only_fields = [
# "content_type",
# "object_id",
"reply_count",
"replies",
]
def get_content_object_url(self, obj):
try:
return obj.content_object.get_api_url()
except:
return None
效果如下
ListView
GET /api/comments/
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/comments/53",
"id": 53,
"content": "reply ++",
"reply_count": 1
},
{
DetailView
GET /api/comments/53
HTTP 200 OK
Allow: GET, PUT, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"id": 53,
"content": "reply ++",
"reply_count": 1,
"replies": [
{
"id": 54,
"content": "123",
"timestamp": "2018-07-18T13:57:07.555000Z"
}
],
"timestamp": "2018-07-18T13:56:27.753000Z",
"content_object_url": "/api/posts/test/"
}