• 递归完成多级评论


    功能:

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

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

    用到的框架: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

    前端页面测试:



  • 相关阅读:
    mysql从一张表查出数据存到另一张表和inner join的用法
    pycharm 看函数列表
    git删除本地所有的更改
    mysql create的几种用法和将字段设为插入时间
    python 装饰器
    pycharm退出unittest模式
    股票基础知识
    linux中查找路径下包含某字符串的所有文件
    SQL distinct用法
    SQL update用法
  • 原文地址:https://www.cnblogs.com/startl/p/12720655.html
Copyright © 2020-2023  润新知