add. 添加递归获取当前部门及所有子部门的 ID 列表工具方法
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
from typing import List
|
||||
|
||||
from django.core.cache import cache
|
||||
|
||||
from users.models import Department
|
||||
|
||||
|
||||
def get_dept_children_ids(dept_id: int) -> List[int]:
|
||||
"""
|
||||
递归获取当前部门及所有子部门的 ID 列表
|
||||
"""
|
||||
# 尝试从缓存获取
|
||||
cache_key = f"dept_tree_{dept_id}"
|
||||
cached_ids = cache.get(cache_key)
|
||||
if cached_ids:
|
||||
return cached_ids
|
||||
|
||||
# 缓存未命中,执行递归逻辑...
|
||||
|
||||
# 1. 初始化列表,包含当前部门 ID
|
||||
dept_ids = [dept_id]
|
||||
|
||||
# 2. 查询直接子部门
|
||||
children = Department.objects.filter(parent_id=dept_id) # 假设外键是 parent_id
|
||||
|
||||
# 3. 递归遍历子部门
|
||||
for child in children:
|
||||
# 递归获取子部门的子部门,并将结果扩展到列表中
|
||||
dept_ids.extend(get_dept_children_ids(child.id))
|
||||
|
||||
# 将结果存入缓存,过期时间设为 12 小时
|
||||
cache.set(cache_key, dept_ids, 12 * 60 * 60)
|
||||
return dept_ids
|
||||
Reference in New Issue
Block a user