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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With