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 pk
s 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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…