Skip to content

Instantly share code, notes, and snippets.

@jmichalicek
Created June 17, 2019 12:16
Show Gist options
  • Save jmichalicek/268edbccd90f3dfb118994408bb8688b to your computer and use it in GitHub Desktop.
Save jmichalicek/268edbccd90f3dfb118994408bb8688b to your computer and use it in GitHub Desktop.
Django ORM select and order based on pre-ordered list of ids
# I can never remember that this is a thing, but it is occasionally useful for me
ids = [5, 2, 3, 1, 4]
order = Case(*[When(id=id, then=pos) for pos, id in enumerate(ids)])
queryset = MyModel.objects.filter(id__in=ids).order_by(order)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment