I'm trying to display a chat log in django. I can get my entire chatlog in the proper order with this query.
latest_chats_list = Chat.objects.order_by('timestamp')
I want the functionality of this line (last 10 elements in order), but django doesn't allow negative indexes.
latest_chats_list = Chat.objects.order_by('timestamp')[-10:]
if I try this line, I get the messages I want, but they're in the wrong order.
latest_chats_list = Chat.objects.order_by('-timestamp')[:10]
This line gives the first 10 chats instead of the most recent.
latest_chats_list = Chat.objects.order_by('-timestamp')[:10].reverse()
last_ten = Chat.objects.all().order_by('-id')[:10]
last_ten_in_ascending_order = reversed(last_ten)
Why not use Django's queryset.reverse()
?
Because it messes with the SQL query, as does queryset.order_by()
. Slicing the queryset ([:10]
) also alters the SQL query, adding LIMIT
and OFFSET
to it. The two can combine in not-obviously-expected ways...
On the other hand, the built-in Python function reversed(iterable)
only changes the way queryset gets iterated over, not effecting the SQL at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With