Skip to content

Instantly share code, notes, and snippets.

@nwjlyons
Created April 12, 2021 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nwjlyons/5ff9266fba0d7cd4cbc45b6a2dfeef6f to your computer and use it in GitHub Desktop.
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.
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