#Best way to get last n items?

6 messages · Page 1 of 1 (latest)

sturdy zenith
#

This works but it seems weird that I'm doing reverse in python. Is there a more idiomatic way to get last n but keep them in the right order?

last_n = list(queryset.order_by('-time_created')[:n])[::-1]
edgy vapor
#

why not queryset.order_by("time_created")[:n]?

#

i.e., flip around the ordering

#

if you also need the stuff in the reverse order, do a second query. That could be more efficient than grabbing the list once, and reversing it in memory

#
last_n = list(queryset.order_by('time_created')[:n])
first_n = list(queryset.order_by('-time_created')[:n])
#

also you might not need the list