我在Django Rest Framework中遇到了问题。
class FeedDetailSerializer(ModelSerializer):
user = UserFeedSerializer(read_only=True)
comment_count = SerializerMethodField(default=0)
comment_list = CommentFeedSerializer(many=True, read_only=True)
class Meta:
model = Feed
fields = [
'id',
'comment_count',
'comment_list',
]
def get_comment_count(self, obj):
comment_count = Comment.objects.filter(feed=obj.id, parent__isnull=True).count()
return comment_count
这是我创建的CommentFeedSerializer:
class CommentFeedSerializer(ModelSerializer):
url = comment_detail_url
class Meta:
model = Comment
fields = [
'url',
'id',
'comment',
'posted_on',
]
使用此序列化程序,我将完成此API:
"comment_count": 2,
"comment_list": [
{
"url": "http://localhost:8000/api/v1/comments/2/",
"id": 2,
"comment": "haha",
"reply_count": 0,
"posted_on": "2017-11-24T10:23:28.353000Z"
},
{
"url": "http://localhost:8000/api/v1/comments/1/",
"id": 1,
"comment": "Good",
"reply_count": 1,
"posted_on": "2017-11-24T09:54:48.680000Z"
}
]
但这很难管理。所以我想将comment_count放入comment_list:commentlist如下所示我该怎么做?
"comment_list": [
"comment_count": 2,
{
"url": "http://localhost:8000/api/v1/comments/2/",
"id": 2,
"comment": "haha",
"reply_count": 0,
"posted_on": "2017-11-24T10:23:28.353000Z"
},
{
"url": "http://localhost:8000/api/v1/comments/1/",
"id": 1,
"comment": "Good",
"reply_count": 1,
"posted_on": "2017-11-24T09:54:48.680000Z"
}
]