-
-
Save balazs-endresz/fd4efda41d4581631f4c to your computer and use it in GitHub Desktop.
Order queryset by list of IDs
This file contains 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
# 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