其实一开始我是很直观地认为是用深度优先来取出层层嵌套的留言的,如下:
# 递归搜索一条留言的所有子留言,深度优先 def dfs(parent, allMsg): childrenList = [] for i in range(len(allMsg)): if allMsg[i]['parent_msg_id'] is not None and allMsg[i]['parent_msg_id'] == parent['id']: allMsg[i]['children'] = dfs(allMsg[i], allMsg) childrenList.append(allMsg[i]) return childrenList这样取出的json格式是这样的:
{ "messages": [ { "id": 5, "date": "2020-05-29 19:09:33", "content": "发的发射点发吖方吖是发是呵等方5爱的非4阿瑟东方 发", "parent_msg_id": null, "user_id": 4, "username": "lisi", "children": [ { "id": 8, "date": "2020-05-29T17:23:37", "content": "哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈呵呵呵呵呵呵", "parent_msg_id": 5, "user_id": 3, "username": "zhangsan", "children": [] } ] }, { "id": 1, "date": "2020-05-29 19:06:21", "content": "fasfdsafas法阿萨德方吖65阿瑟东方5是的发", "parent_msg_id": null, "user_id": 1, "username": "student", "children": [ { "id": 2, "date": "2020-05-29T19:08:41", "content": "fasdfasdf发生的法撒旦飞洒多发点房地产", "parent_msg_id": 1, "user_id": 4, "username": "lisi", "children": [ { "id": 4, "date": "2020-05-29T19:09:14", "content": "发送端非场地萨擦手d5asd32 1dads\r\ndsac十多次ds出错", "parent_msg_id": 2, "user_id": 8, "username": "mike", "children": [ { "id": 6, "date": "2020-05-29T19:09:56", "content": "而离开离开邻居哦i据哦i报价哦v保健品45465", "parent_msg_id": 4, "user_id": 6, "username": "zhaoliu", "children": [ { "id": 7, "date": "2020-05-29T19:29:29", "content": "hfhf2h22h222223232", "parent_msg_id": 6, "user_id": 1, "username": "student", "children": [] } ] } ] }, { "id": 3, "date": "2020-05-29T19:08:56", "content": "奋发恶法撒打发士大夫士大夫是大 大师傅撒", "parent_msg_id": 2, "user_id": 2, "username": "teacher", "children": [] }, { "id": 9, "date": "2020-05-29T17:27:13", "content": "alalla啦啦啦啦啦啦来的队列李大水泛滥的萨拉发 的 第三方哈l", "parent_msg_id": 2, "user_id": 7, "username": "joke", "children": [] } ] } ] } ], "status_code": 200 }但仔细一想,实际页面展示的时候肯定不能这样一层层无限地嵌套下去,否则留言多了页面就装不下了,于是还是改成了两层留言的格式,第二层使用广度优先搜索将树转为列表存储。
2.2 新增留言接口前台提供留言内容、留言者id以及父留言的id(如果不是回复信息的话就是空)
import datetime @require_http_methods(['POST']) def insertMsg(request): response = {} try: request.POST = request.POST.copy() request.POST['date'] = datetime.datetime.now() msg = Message() msg.date = request.POST.get('date') msg.content = request.POST.get('content') msg.parent_msg_id = request.POST.get('parent_msg_id') msg.user_id = request.POST.get('user_id') msg.save() response['msg'] = 'success' response['status_code'] = 200 except Exception as e: response['error'] = str(e) response['status_code'] = 500 return JsonResponse(response) 3.前台设计有了后台提供的数据,前台展示就比较简单了。
留言板块的设计我使用了Ant Design的留言组件。