From 2aefecec04df1aa0fd4fca51f6a2a506953b8270 Mon Sep 17 00:00:00 2001 From: xinwen Date: Thu, 26 Nov 2020 10:34:27 +0800 Subject: [PATCH] =?UTF-8?q?perf(User):=20=E7=94=A8=E6=88=B7=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E5=9C=A8=E5=A4=A7=E8=A7=84=E6=A8=A1=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E6=83=85=E5=86=B5=E4=B8=8B=E6=85=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/users/api/user.py | 17 +++++++++++++---- apps/users/models/user.py | 18 +++++++----------- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/apps/users/api/user.py b/apps/users/api/user.py index 65bd8f4d1..b0b209e19 100644 --- a/apps/users/api/user.py +++ b/apps/users/api/user.py @@ -6,8 +6,8 @@ from rest_framework.decorators import action from rest_framework import generics from rest_framework.response import Response from rest_framework_bulk import BulkModelViewSet +from django.db.models import Prefetch -from common.db.aggregates import GroupConcat from common.permissions import ( IsOrgAdmin, IsOrgAdminOrAppUser, CanUpdateDeleteUser, IsSuperUser @@ -44,9 +44,18 @@ class UserViewSet(CommonApiMixin, UserQuerysetMixin, BulkModelViewSet): extra_filter_backends = [OrgRoleUserFilterBackend] def get_queryset(self): - return super().get_queryset().annotate( - gc_m2m_org_members__role=GroupConcat('m2m_org_members__role'), - ).prefetch_related('groups') + queryset = super().get_queryset().prefetch_related( + 'groups' + ) + if current_org.is_real(): + # 为在列表中计算用户在真实组织里的角色 + queryset = queryset.prefetch_related( + Prefetch( + 'm2m_org_members', + queryset=OrganizationMember.objects.filter(org__id=current_org.id) + ) + ) + return queryset def send_created_signal(self, users): if not isinstance(users, list): diff --git a/apps/users/models/user.py b/apps/users/models/user.py index 81f0f593b..56c979738 100644 --- a/apps/users/models/user.py +++ b/apps/users/models/user.py @@ -170,22 +170,18 @@ class RoleMixin: from orgs.models import ROLE as ORG_ROLE if not current_org.is_real(): + # 不是真实的组织,取 User 本身的角色 if self.is_superuser: return [ORG_ROLE.ADMIN] else: return [ORG_ROLE.USER] - if hasattr(self, 'gc_m2m_org_members__role'): - names = self.gc_m2m_org_members__role - if isinstance(names, str): - roles = set(self.gc_m2m_org_members__role.split(',')) - else: - roles = set() - else: - roles = set(self.m2m_org_members.filter( - org_id=current_org.id - ).values_list('role', flat=True)) - roles = list(roles) + # 是真实组织,取 OrganizationMember 中的角色 + roles = [ + org_member.role + for org_member in self.m2m_org_members.all() + if org_member.org_id == current_org.id + ] roles.sort() return roles