Browse Source

perf(User): 用户列表在大规模数据情况下慢

pull/5113/head
xinwen 4 years ago committed by Jiangjie.Bai
parent
commit
df2f1b3e6e
  1. 17
      apps/users/api/user.py
  2. 18
      apps/users/models/user.py

17
apps/users/api/user.py

@ -6,8 +6,8 @@ from rest_framework.decorators import action
from rest_framework import generics from rest_framework import generics
from rest_framework.response import Response from rest_framework.response import Response
from rest_framework_bulk import BulkModelViewSet from rest_framework_bulk import BulkModelViewSet
from django.db.models import Prefetch
from common.db.aggregates import GroupConcat
from common.permissions import ( from common.permissions import (
IsOrgAdmin, IsOrgAdminOrAppUser, IsOrgAdmin, IsOrgAdminOrAppUser,
CanUpdateDeleteUser, IsSuperUser CanUpdateDeleteUser, IsSuperUser
@ -44,9 +44,18 @@ class UserViewSet(CommonApiMixin, UserQuerysetMixin, BulkModelViewSet):
extra_filter_backends = [OrgRoleUserFilterBackend] extra_filter_backends = [OrgRoleUserFilterBackend]
def get_queryset(self): def get_queryset(self):
return super().get_queryset().annotate( queryset = super().get_queryset().prefetch_related(
gc_m2m_org_members__role=GroupConcat('m2m_org_members__role'), 'groups'
).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): def send_created_signal(self, users):
if not isinstance(users, list): if not isinstance(users, list):

18
apps/users/models/user.py

@ -170,22 +170,18 @@ class RoleMixin:
from orgs.models import ROLE as ORG_ROLE from orgs.models import ROLE as ORG_ROLE
if not current_org.is_real(): if not current_org.is_real():
# 不是真实的组织,取 User 本身的角色
if self.is_superuser: if self.is_superuser:
return [ORG_ROLE.ADMIN] return [ORG_ROLE.ADMIN]
else: else:
return [ORG_ROLE.USER] return [ORG_ROLE.USER]
if hasattr(self, 'gc_m2m_org_members__role'): # 是真实组织,取 OrganizationMember 中的角色
names = self.gc_m2m_org_members__role roles = [
if isinstance(names, str): org_member.role
roles = set(self.gc_m2m_org_members__role.split(',')) for org_member in self.m2m_org_members.all()
else: if org_member.org_id == current_org.id
roles = set() ]
else:
roles = set(self.m2m_org_members.filter(
org_id=current_org.id
).values_list('role', flat=True))
roles = list(roles)
roles.sort() roles.sort()
return roles return roles

Loading…
Cancel
Save