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

pull/5113/head
xinwen 4 years ago committed by Jiangjie.Bai
parent f26b7a470a
commit df2f1b3e6e

@ -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):

@ -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

Loading…
Cancel
Save