Skip to content

Commit 4bd284b

Browse files
committed
refactor: optimize user retrieval in UserRoleAssignmentSerializer by using a user map
1 parent dc520d0 commit 4bd284b

1 file changed

Lines changed: 12 additions & 26 deletions

File tree

openedx_authz/rest_api/v1/serializers.py

Lines changed: 12 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66
from openedx_authz.api.data import RoleAssignmentData
77
from openedx_authz.rest_api.enums import SortField, SortOrder
8-
from openedx_authz.rest_api.utils import get_user_by_username_or_email
98
from openedx_authz.rest_api.v1.fields import CommaSeparatedListField, LowercaseCharField
109

1110
User = get_user_model()
@@ -96,38 +95,25 @@ def __init__(self, *args, **kwargs):
9695
super().__init__(*args, **kwargs)
9796
self._user_cache = {}
9897

99-
def _get_user(self, obj: RoleAssignmentData) -> User | None:
100-
"""
101-
Retrieve and cache the user object for the given role assignment to minimize database queries.
102-
103-
Args:
104-
obj (RoleAssignmentData): The role assignment data containing the user identifier.
105-
106-
Returns:
107-
User | None: The corresponding User object if found, otherwise None.
108-
"""
109-
username = obj.subject.username
110-
if username not in self._user_cache:
111-
try:
112-
self._user_cache[username] = get_user_by_username_or_email(username)
113-
except User.DoesNotExist:
114-
self._user_cache[username] = None
115-
return self._user_cache[username]
98+
def _get_user(self, obj) -> User | None:
99+
"""Get the user object for the given role assignment."""
100+
user_map = self.context.get("user_map", {})
101+
return user_map.get(obj.subject.username)
116102

117103
def get_username(self, obj: RoleAssignmentData) -> str:
104+
"""Get the username for the given role assignment."""
118105
return obj.subject.username
119106

120-
def get_full_name(self, obj: RoleAssignmentData) -> str:
107+
def get_full_name(self, obj) -> str:
108+
"""Get the full name for the given role assignment."""
121109
user = self._get_user(obj)
122-
if not user or not hasattr(user, "profile"):
123-
return ""
124-
return getattr(user.profile, "name", "")
110+
return getattr(user.profile, "name", "") if user and hasattr(user, "profile") else ""
125111

126-
def get_email(self, obj: RoleAssignmentData) -> str:
112+
def get_email(self, obj) -> str:
113+
"""Get the email for the given role assignment."""
127114
user = self._get_user(obj)
128-
if not user:
129-
return ""
130-
return getattr(user, "email", "")
115+
return getattr(user, "email", "") if user else ""
131116

132117
def get_roles(self, obj: RoleAssignmentData) -> list[str]:
118+
"""Get the roles for the given role assignment."""
133119
return [role.external_key for role in obj.roles]

0 commit comments

Comments
 (0)