Skip to content

Instantly share code, notes, and snippets.

@balazs-endresz
balazs-endresz / .py
Last active February 12, 2024 15:15
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: