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)