[Django]-Betterway to retrieve recent 10 items from database in django

4👍

This shouldn’t take long at all, even on large tables. Did you define a default ordering on the Meta class of the model? Perhaps it orders on a non-indexed field per default, which would be a reason for the slowdown you’re seeing.

Anyway, to get the most recent entries, order them by the primary key (which is guaranteed to be indexed):

itemobjects = Items.objects.all().order_by('-pk')[:10]

/edit: just a tip: it is a convention to give model classes singular names, e.g. Item instead of Items.

Leave a comment