Django QuerySet Custom Ordering by ID

Viewed 5954

Given a list of ids/pks, I'd like to generate a QuerySet of objects ordered by the index in the list.

Normally I'd begin with:

pk_list = [5, 9, 2, 14]
queryset = MyModel.objects.filter(pk__in=pk_list)

This of course returns the objects, but in the order of the models meta ordering property, and I wish to get the records in the order of the pks in pk_list.

The end result has to be one QuerySet object (not a list), as I wish to pass the ordered QuerySet to Django's ModelMultipleChoiceField form field.

3 Answers

In Django 2.2, I was able to order QuerySet based on an order list using following approach:

pk_list = [4, 23, 10, 9]
preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pk_list)])
new_qs = qs.filter(pk__in=pk_list).order_by(preserved)
Related