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_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 = "<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)另外有需要云服務器可以了解下創新互聯scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業上云的綜合解決方案,具有“安全穩定、簡單易用、服務可用性高、性價比高”等特點與優勢,專為企業上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。

網頁名稱:多級評論的實現-創新互聯
URL標題:http://www.yijiale78.com/article42/pihhc.html
成都網站建設公司_創新互聯,為您提供電子商務、網站排名、企業建站、服務器托管、標簽優化、網站營銷
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯