Better get last 10 items from database in django

I use the following query to retrieve 10 items from my database

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

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

+3
source share
1 answer

It does not take much time, even on large tables. Have you defined the default order in the Metamodel class ? Perhaps he orders a default non-indexed field, which will cause the slowdown you see.

In any case, to get the most recent entries, order them using the primary key (which will be indexed):

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

/edit: : , , . Item Items.

+4

All Articles