From ab6c0a9b4960fdbdfe16239523bfc989131b6a94 Mon Sep 17 00:00:00 2001 From: ngfchl Date: Fri, 10 Apr 2026 19:00:21 +0800 Subject: [PATCH] =?UTF-8?q?add.=20=E6=B7=BB=E5=8A=A0=E9=80=92=E5=BD=92?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E5=BD=93=E5=89=8D=E9=83=A8=E9=97=A8=E5=8F=8A?= =?UTF-8?q?=E6=89=80=E6=9C=89=E5=AD=90=E9=83=A8=E9=97=A8=E7=9A=84=20ID=20?= =?UTF-8?q?=E5=88=97=E8=A1=A8=E5=B7=A5=E5=85=B7=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/dept_utils.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 utils/dept_utils.py diff --git a/utils/dept_utils.py b/utils/dept_utils.py new file mode 100644 index 0000000..b696a08 --- /dev/null +++ b/utils/dept_utils.py @@ -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