Skip to content

Commit dc520d0

Browse files
committed
feat: add get_user_map function for optimized batch user lookups
1 parent 7ad8f6a commit dc520d0

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

openedx_authz/rest_api/utils.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,26 @@ def _decorator(func_or_class):
3131
return _decorator
3232

3333

34+
def get_user_map(usernames: list[str]) -> dict[str, User]:
35+
"""
36+
Retrieve a dictionary mapping usernames to User objects for efficient batch lookups.
37+
38+
This function performs a single optimized database query to fetch multiple users,
39+
making it ideal for scenarios where we need to look up several users at once
40+
(e.g., when serializing multiple user role assignments).
41+
42+
Args:
43+
usernames (list[str]): List of usernames to retrieve. Duplicates are automatically
44+
handled by the database query.
45+
46+
Returns:
47+
dict[str, User]: Dictionary mapping each username to its corresponding User object.
48+
Only users that exist in the database are included in the returned dictionary.
49+
"""
50+
users = User.objects.filter(username__in=usernames).select_related("profile")
51+
return {user.username: user for user in users}
52+
53+
3454
def get_user_by_username_or_email(username_or_email: str) -> User:
3555
"""
3656
Retrieve a user by their username or email address.

0 commit comments

Comments
 (0)