E
E
ekzotika2021-03-29 11:53:23
Django
ekzotika, 2021-03-29 11:53:23

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

1 answer(s)
S
Sergey Gornostaev, 2021-03-29
@ekzotika

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))

But you can also use the database tools:
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 question

Ask a Question

731 491 924 answers to any question