django实现目录树结构

目录树结构获取方案
一次性查询所有用户信息

 group_list = []
 # 一次性读取所有用户信息
 group_object_list = Department.objects.filter(is_deleted=False)
 for group in group_object_list:
     if group.parent_dept_id != 0:
         continue
     group_dict = dep_to_dict(group) # 将用户转换成对应的格式字典
     group_info = dept_menu(group_object_list, group_dict)
     group_list.append(group_info)
 return group_list

通过递归实现获取当前部门下面所有子部门的信息

def dept_menu(group_list, dept_root):
    dept_info_list = []
    for group in group_list:
       # 获取当前部门的所有子部门
        if group.parent_dept_id != dept_root['id']:
            continue
        dept_info = dep_to_dict(group)
        ms = dept_menu(group_list, dept_info)
        dept_info_list.append(ms)
    dept_root['children'] = dept_info_list
    return dept_root

信息转换

def dep_to_dict(group):
    dept_info = {
        'id': group.id,
        'dept_name': group.name,
        'parent_dept_id': group.parent_dept_id,
        'children': []
    }
    return dept_info

返回效果

[
    {
        "id": 1,
        "dept_name": "数据中台",
        "parent_dept_id": 0,
        "children": [
            {
                "id": 2,
                "dept_name": "爬虫组",
                "parent_dept_id": 1,
                "children": [
                    {
                        "id": 5,
                        "dept_name": "运维组",
                        "parent_dept_id": 2,
                        "children": []
                    },
                    {
                        "id": 6,
                        "dept_name": "系统组",
                        "parent_dept_id": 2,
                        "children": []
                    }
                ]
            },
            {
                "id": 3,
                "dept_name": "BI组",
                "parent_dept_id": 1,
                "children": []
            },
            {
                "id": 4,
                "dept_name": "算法组",
                "parent_dept_id": 1,
                "children": []
            }
        ]
    }
]
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值