Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

betterway to retrieve recent 10 items from database in django

I use the query below for retrieving 10 items from my database

    itemobjects = Items.objects.all()[:10]

Is there a better way to do this? Because when number of items in my database increases the above query is very slow and takes around 1-2 seconds

like image 280
shanks Avatar asked Dec 31 '25 18:12

shanks


1 Answers

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.

like image 133
Benjamin Wohlwend Avatar answered Jan 02 '26 07:01

Benjamin Wohlwend



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!