Created
April 12, 2021 13:54
-
-
Save nwjlyons/5ff9266fba0d7cd4cbc45b6a2dfeef6f to your computer and use it in GitHub Desktop.
Django QuerySet function that will return up to `max_length` objects from the `selected` queryset, falling back to the `fallback` queryset to make up the numbers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_selected_or_fallback(*, selected: QuerySet, fallback: QuerySet, max_length: int) -> list: | |
""" | |
Return up to `max_length` objects from the `selected` queryset, | |
falling back to the `fallback` queryset to make up the numbers. | |
""" | |
selected = list(selected[:max_length]) | |
fallback = list(fallback.exclude(id__in=[obj.id for obj in selected])[:max_length]) | |
return (selected + fallback)[:max_length] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment