zoukankan      html  css  js  c++  java
  • 递归完成多级评论

    功能:

    通过递归找到根评论,依次再找到一级评论.....

    为了方便起见,没有创建数据库

    用到的框架:Django

    views代码:

    from django.shortcuts import render,HttpResponse

    # Create your views here.
    class Node:
    @staticmethod
    def digui(ret,row):
    for rt in ret:
    if rt["id"]==row["parent_id"]:
    row['children']=[]
    rt['children'].append(row)
    return
    else:
    Node.digui(rt['children'],row)


    @staticmethod #加上这个是为了不用self
    def create_tree(comment_list):
    ret=[]
    for row in comment_list:#遍历comment_list
    if not row['parent_id']:
    row['children']=[]
    ret.append(row)#将parent_id为None的加入到ret列表当中
    else:
    Node.digui(ret,row)
    # else:
    # for i in row:#遍历每一行
    # if row['parent_id']==i['id']:
    # row['children']=[]
    # i['children'].append(row)
    # else:
    # for j in i['children']:
    # if j['parent_id']==i['children']['id']:
    # i['children']['children']=[]
    # i['children']['children'].append(j)






    return ret


    def comment(req):
    comment_list=[
    {"id":1,"content":"python最厉害","user":"来星星","parent_id":None},
    {"id":2,"content":"GO最厉害","user":"来星星","parent_id":None},
    {"id":3,"content":"C++最厉害","user":"来星星","parent_id":None},
    {"id":4,"content":"你最厉害","user":"琪琪","parent_id":1},
    {"id":5,"content":"老师最厉害","user":"娜娜","parent_id":1},
    {"id":6,"content":"吴建华厉害","user":"吴建华","parent_id":4},
    {"id":7,"content":"心悦最厉害","user":"心悦","parent_id":2},
    {"id":8,"content":"心悦最帅","user":"心悦","parent_id":3},
    {"id":9,"content":"好好好,心悦最帅公认的","user":"来星星","parent_id":8},

    ]
    comment_tree=Node.create_tree(comment_list)
    for i in comment_tree:
    print(i)
    return HttpResponse("comment")
    url列表:
    urlpatterns = [
    path('admin/', admin.site.urls),
    path("comment.html/",views.comment)
    ]
    后端接收到的结果:

    {'content': 'python最厉害', 'parent_id': None, 'id': 1, 'children': [{'content': '你最厉害', 'parent_id': 1, 'id': 4, 'children': [{'content': '吴建华厉害', 'parent_id': 4, 'id': 6, 'children': [], 'user': '吴建华'}], 'user': '琪琪'}, {'content': '老师最厉害', 'parent_id': 1, 'id': 5, 'children': [], 'user': '娜娜'}], 'user': '来星星'}


    {'content': 'GO最厉害', 'parent_id': None, 'id': 2, 'children': [{'content': '心悦最厉害', 'parent_id': 2, 'id': 7, 'children': [], 'user': '心悦'}], 'user': '来星星'}


    {'content': 'C++最厉害', 'parent_id': None, 'id': 3, 'children': [{'content': '心悦最帅', 'parent_id': 3, 'id': 8, 'children': [{'content': '好好好,心悦最帅公认的', 'parent_id': 8, 'id': 9, 'children': [], 'user': '来星星'}], 'user': '心悦'}], 'user': '来星星'}
    [17/Apr/2020 16:04:58] "GET /comment.html/ HTTP/1.1" 200 7

    前端页面测试:



  • 相关阅读:
    vue 按需加载
    需要打印真实尺寸大小等需求的,css的单位可以使用mm等做单位
    d3 比例尺
    d3 根据数据绘制svg
    d3 svg简单学习
    d3 使用随机数据生成条形图
    d3 画简单的柱形图
    d3 使用数据
    d3 数据绑定
    d3 添加元素相关api
  • 原文地址:https://www.cnblogs.com/startl/p/12720655.html
Copyright © 2011-2022 走看看