Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the last n objects of a django query?

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()
like image 758
user2601064 Avatar asked Jan 08 '23 22:01

user2601064


1 Answers

last_ten = Chat.objects.all().order_by('-id')[:10]
last_ten_in_ascending_order = reversed(last_ten)

Edit (from comments)

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.

like image 57
Ajay Gupta Avatar answered Jan 10 '23 10:01

Ajay Gupta