目录树结构获取方案
一次性查询所有用户信息
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": []
}
]
}
]