Answer the question
In order to leave comments, you need to log in
How to sort Queryset according to list?
How to sort Queryset according to list?
For example, I do this:
And you need the elements in the queryset to go in order, that is, first id=3, then id=1, then id=8, etc.
But in the end, you need to leave the queryset, not the list!
m.objects.filter(id__in=[3,1,8])
Answer the question
In order to leave comments, you need to log in
If the selection is small, then the easiest way is to simply sort the list obtained from the queryset:
ids = [3,1,8]
result = sorted(m.objects.filter(id__in=ids), key=lambda i: ids.index(i.pk))
ids = [3,1,8]
conditions = Case(*[When(pk=pk, then=n) for n, pk in enumerate(ids)])
queryset = m.objects.filter(id__in=ids).order_by(conditions)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question