第一种:

comment_list=models.Comment.objects.filter(news_id=new_id)ret=[] # 最终拿到的数据comment_list_dict={} # 构建的中间字典for row in comment_list: # 通过查到的数据中的id作为key,每一行数据作为value生成一个字典 row.update({"children":[]}) # 构建一个键children对应一个空列表 comment_list_dict[row["id"]]=row # 将id作为键,当前行作为值存到该字典中for item in comment_list: # 遍历一遍取到的数据列表 parrent_row=comment_list_dict.get(item["parent_id"]) # 拿到当前行对应的父亲的地址 if not parrent_row: # 如果父亲是None,则直接进入ret中 ret.append(item) else: # 否则,将这行append到父亲的children中 parrent_row["children"].append(item) # 重点在这一行,用到了上面提到的第一个知识点print(ret)第二种:

from django.utils.safestring import mark_safe# 递归查找父节点def find_father(dic, comment_obj): # 对字典中的每一组元素进行循环操作 for k, v_dic in dic.items(): # 如果k等于comment_obj的父节点,那么表示找到了父亲。 if k == comment_obj.parent_comment: # 找到了父亲,认祖归宗,把自己归位到父亲下面,并给将来的儿子留个位置 dic[k][comment_obj] = {} # 找到了父亲,处理完毕,返回 else: # 刚才没找到,剥一层,接着往下找。 find_father(dic[k], comment_obj)# 递归生成html字符串def generate_comment_html(sub_comment_dic, margin_left_val): # 先创建一个空字符串 html = "" # 对传入的字典进行循环操作 for k, v_dic in sub_comment_dic.items(): html += "<div style='margin-left:%spx'><span class='nickname'>" % margin_left_val + k.name + "</span>" + "<time class='submit-date'>" + str(k.created_time.strftime('%Y-%m-%d %H:%M:%S')) + "<div class='text'>" + k.text + '</div></div><hr>' # html += "<div style='margin-left:%spx' class='comment-node'>" % margin_left_val + k.text + "</div>" # 有可能v_dic中依然有元素, 递归继续加 if v_dic: html += generate_comment_html(v_dic, margin_left_val+35) # 循环完成最后返回html return html# 生成层级评论@register.simple_tagdef build_comment_tree(comment_list): # 定义一个空字典用来保存转换之后的结果 comment_dic = {} # 对comment_list中的每个元素进行循环 for comment_obj in comment_list: # 判断comment_obj是否存在父节点。如果没有,这把该评论作为第一个节点 if comment_obj.parent_comment is None: comment_dic[comment_obj] = {} else: # 否则去找该对象的父节点。 find_father(comment_dic, comment_obj) # 上面执行完毕,comment_dic中会有转换好的结果 # 开始拼接html字符串 html = "<ul class='comment-list list-unstyled'>" # 规定一个margin left,每次有递归的时候就往右缩进一点。 margin_left = 0 # 对comment_dic中的每一组元素进行操作 for k,v in comment_dic.items(): # 第一层html html += "<li class='comment-item'><span class='nickname'>" + k.name + "</span>" + "<time class='submit-date'>" + str(k.created_time.strftime('%Y-%m-%d %H:%M:%S')) + "<div class='text'>" + k.text + '</div></li>' # 通过递归把他的儿子加上 html += generate_comment_html(v, margin_left+35) # 最后把ul关上 html += " </ul>" # 关掉转义 return mark_safe(html)