How to get the last n django request objects?

I am trying to show chat log in django. I can get my entire chat log in the correct order with this request.

latest_chats_list = Chat.objects.order_by('timestamp')

I want the functionality of this line (the last 10 elements are fine), but django does not 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 are in the wrong order.

latest_chats_list = Chat.objects.order_by('-timestamp')[:10]

This line gives the first 10 chats instead of the last.

latest_chats_list = Chat.objects.order_by('-timestamp')[:10].reverse()
+4
source share
1 answer
last_ten = Chat.objects.all().order_by('-id')[:10]
last_ten_in_ascending_order = reversed(last_ten)

Edit (from comments)

Why not use Django queryset.reverse()?

SQL-, queryset.order_by(). ([:10]) SQL-, LIMIT OFFSET. ...

, Python reversed(iterable) queryset, SQL .

+5

Source: https://habr.com/ru/post/1598537/


All Articles