Is it possible to sort queryset without hitting the db again?

Is there any approach to avoid hitting db when the queryset needs to be returned in a specific order?

If a queryset would be returned when a page is loaded

qs = Student.objects.all()[start:end]

But it also provides UI for users to view the query in ascending or descending order. So, at Django server.

Queries should be performed

qs = Student.objects.all()[start:end]
qs2 = Student.objects.filter(id__in=qs).order_by("-id")  

To reduce the db hitting, is there any other better approach to avoid frequent query and db hit?

I wonder I would store the query result in browser and return the results but it looks so complex...

You can use python's built in function sorted(). You have to pass iterable object and key function to sorted() function.

In your case, you can try:

qs = Student.objects.all()[start:end]
sorted_qs = sorted(qs, key=lambda obj:
Back to Top