File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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+
3454def get_user_by_username_or_email (username_or_email : str ) -> User :
3555 """
3656 Retrieve a user by their username or email address.
You can’t perform that action at this time.
0 commit comments