Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django query get last n records

Tags:

django

Lets say I am implementing a message stream, records sort by ID ascending order, each fetch request, I want to only allow to fetch the most latest 10 records.

I tried:

Messages.objects.filter(since=since)[:-10] 

And I had an error saying Negative Indexing is not supported.

My current work around is sort ID descending order, and then run:

Messages.objects.filter(since=since)[:10] 

But this requires the front end to reverse the order again.

My question is, is there a elegant way to do it?

like image 663
James Lin Avatar asked Dec 12 '13 22:12

James Lin


1 Answers

You can pass your queryset to reversed:

last_ten = Messages.objects.filter(since=since).order_by('-id')[:10] last_ten_in_ascending_order = reversed(last_ten) 
like image 55
Robert Kajic Avatar answered Sep 17 '22 19:09

Robert Kajic