Skip to content

Instantly share code, notes, and snippets.

@balazs-endresz
Last active February 12, 2024 15:15
Show Gist options
  • Save balazs-endresz/fd4efda41d4581631f4c to your computer and use it in GitHub Desktop.
Save balazs-endresz/fd4efda41d4581631f4c to your computer and use it in GitHub Desktop.
Order queryset by list of IDs
# https://stackoverflow.com/questions/4916851/django-get-a-queryset-from-array-of-ids-in-specific-order/37648265#37648265
from django.db.models import Case, When
pk_list = [10, 2, 1]
preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pk_list)])
queryset = MyModel.objects.filter(pk__in=pk_list).order_by(preserved)
# pre django 1.8:
# def order_by_ids(queryset, ids):
# db_column = queryset.model._meta.pk.db_column
# ordering = 'CASE %s END' % ' '.join(['WHEN "%s"=%s THEN %s' % (db_column, pk, i) for i, pk in enumerate(ids)])
# return queryset.filter(pk__in=ids).extra(select={'ordering': ordering}, order_by=('ordering',))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment