diff --git a/allianceauth/framework/api/user.py b/allianceauth/framework/api/user.py index 51b314ae..7118ae94 100644 --- a/allianceauth/framework/api/user.py +++ b/allianceauth/framework/api/user.py @@ -10,24 +10,39 @@ from allianceauth.authentication.models import CharacterOwnership from allianceauth.eveonline.models import EveCharacter -def get_all_characters_from_user(user: User) -> list: +def get_all_characters_from_user(user: User, main_first: bool = False) -> list: """ - Get all characters from a user or an empty list - when no characters are found for the user or the user is None + Get all characters from a user + This function retrieves all characters associated with a given user, optionally ordering them + with the main character first. + If the user is None, an empty list is returned. - :param user: - :type user: - :return: - :rtype: + :param user: The user whose characters are to be retrieved + :type user: User + :param main_first: If True, the main character will be listed first + :type main_first: bool + :return: A list of EveCharacter objects associated with the user + :rtype: list[EveCharacter] """ if user is None: return [] try: - characters = [ - char.character for char in CharacterOwnership.objects.filter(user=user) - ] + if main_first: + characters = [ + char.character + for char in CharacterOwnership.objects.filter(user=user).order_by( + "-character__userprofile", "character__character_name" + ) + ] + else: + characters = [ + char.character + for char in CharacterOwnership.objects.filter(user=user).order_by( + "character__character_name" + ) + ] except AttributeError: return [] diff --git a/docs/development/custom/framework/api.md b/docs/development/custom/framework/api.md index 576a5373..f095447e 100644 --- a/docs/development/custom/framework/api.md +++ b/docs/development/custom/framework/api.md @@ -43,7 +43,7 @@ if the `EveCharacter` has no user. ### get_all_characters_from_user -This is to get all character objects (`EveCharacter`) of a user. +This is to get all character objects (`EveCharacter`) of a user (alphabetically sorted). Given we have a `User` object called `my_user` and we want to get all characters: @@ -51,12 +51,16 @@ Given we have a `User` object called `my_user` and we want to get all characters # Alliance Auth from allianceauth.framework.api.user import get_all_characters_from_user -characters = get_all_characters_from_user(user=my_user) +characters = get_all_characters_from_user(user=my_user, main_first=False) ``` Now, `characters` is a `list` containing all `EveCharacter` objects of the user. If the user is `None`, an empty `list` will be returned. +The second parameter `main_first` is optional and defaults to `False`. +If set to `True`, the function will return the main character as the first +item in the list of characters. + ### get_main_character_from_user This is to get the main character object (`EveCharacter`) of a user.