多级评论的实现-成都快上网建站

多级评论的实现

第一种:

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 += "
" % margin_left_val + k.name + "" + "

' # html += "
" % margin_left_val + k.text + "
" # 有可能v_dic中依然有元素, 递归继续加 if v_dic: html += generate_comment_html(v_dic, margin_left_val+35) # 循环完成最后返回html return html # 生成层级评论 @register.simple_tag def 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 = "
    " # 规定一个margin left,每次有递归的时候就往右缩进一点。 margin_left = 0 # 对comment_dic中的每一组元素进行操作 for k,v in comment_dic.items(): # 第一层html html += "
  • " + k.name + "" + "
  • ' # 通过递归把他的儿子加上 html += generate_comment_html(v, margin_left+35) # 最后把ul关上 html += "
" # 关掉转义 return mark_safe(html)

网页标题:多级评论的实现
网站链接:http://kswjz.com/article/ijpoes.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流