|
7 | 7 | @desc: |
8 | 8 | """ |
9 | 9 | import re |
| 10 | +from collections import defaultdict |
10 | 11 | from itertools import product |
11 | 12 |
|
12 | 13 | from django.db import transaction |
@@ -163,9 +164,38 @@ def list(self, with_valid=True): |
163 | 164 | def page(self, current_page: int, page_size: int, with_valid=True): |
164 | 165 | if with_valid: |
165 | 166 | self.is_valid(raise_exception=True) |
166 | | - return page_search(current_page, page_size, |
167 | | - self.get_query_set(), |
168 | | - post_records_handler=lambda u: UserInstanceSerializer(u).data) |
| 167 | + result = page_search(current_page, page_size, |
| 168 | + self.get_query_set(), |
| 169 | + post_records_handler=lambda u: UserInstanceSerializer(u).data) |
| 170 | + role_model = DatabaseModelManage.get_model("role_model") |
| 171 | + user_role_relation_model = DatabaseModelManage.get_model("workspace_user_role_mapping") |
| 172 | + |
| 173 | + def _get_user_roles(user_ids): |
| 174 | + if not (role_model and user_role_relation_model): |
| 175 | + return {} |
| 176 | + |
| 177 | + # 获取所有相关角色关系,并预加载角色信息 |
| 178 | + user_role_relations = ( |
| 179 | + user_role_relation_model.objects |
| 180 | + .filter(user_id__in=user_ids) |
| 181 | + .select_related('role_id') # 预加载外键数据 |
| 182 | + ) |
| 183 | + |
| 184 | + # 构建用户ID到角色名称列表的映射 |
| 185 | + user_role_mapping = defaultdict(list) |
| 186 | + for relation in user_role_relations: |
| 187 | + user_role_mapping[relation.user_id].append(relation.role_id.name) |
| 188 | + |
| 189 | + return user_role_mapping |
| 190 | + |
| 191 | + if role_model and user_role_relation_model: |
| 192 | + user_ids = [user['id'] for user in result['records']] |
| 193 | + user_role_mapping = _get_user_roles(user_ids) |
| 194 | + |
| 195 | + # 将角色信息添加回用户数据中 |
| 196 | + for user in result['records']: |
| 197 | + user['role'] = user_role_mapping.get(user['id'], []) |
| 198 | + return result |
169 | 199 |
|
170 | 200 | @valid_license(model=User, count=2, |
171 | 201 | message=_( |
|
0 commit comments