Django - reorder requests after slicing

I am extracting the last 5 rows from the Foo model, which is ordered by the datetime field.

qs = Foo.objects.all()[:5] 

In the next step, I want to change the order of the requests to some other criteria (in fact, using the same date and time field in the opposite direction). But reordering after a piece is not allowed. reverse () cancels the first order, giving me a set of difference requests. Is there a way to accomplish what I want without creating a list from a set of queries and making use of it?

+6
django django-orm django-queryset
source share
3 answers

No, there is no way to do this. order_by is an operation in the database, but when you cut the query, it is evaluated and does not return to the database after that.

It looks like you already know the solution: run reversed() on evaluated qs.

 qs = reversed(Foo.objects.all()[:5]) 
+10
source share

order_by gives you the SQL upload to the database. You already use this and then chop it. At this point, the results are output to memory. If you want to change your order, you need to use sorting in Python memory for this, rather than ORM sorting in the database.

In your case, Daniel has already given a better solution: since you just want to sort by the same field, but in a different order, just change the list that you have:

 qs = Foo.objects.all()[:5] objs = reversed(qs) 

If you needed to sort some other field, you should use the sorted () function using a special function:

 qs = Foo.objects.all()[:5] objs = sorted(qs, key=lambda o: o.some_other_field) 
+13
source share

Late answer, but this only worked for me:

 import random sorted(queryset[:10], key=lambda x: random.random()) 
+1
source share

All Articles