Issue
I want to take the last 10 instances of a model and have this code:
Model.objects.all().order_by('-id')[:10]
Is it true that firstly pick up all instances, and then take only 10 last ones? Is there any more effective method?
Solution
Django querysets are lazy. That means a query will hit the database only when you specifically ask for the result.
So until you print or actually use the result of a query you can filter further with no database access.
As you can see below your code only executes one sql query to fetch only the last 10 items.
In [19]: import logging
In [20]: l = logging.getLogger('django.db.backends')
In [21]: l.setLevel(logging.DEBUG)
In [22]: l.addHandler(logging.StreamHandler())
In [23]: User.objects.all().order_by('-id')[:10]
(0.000) SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" ORDER BY "auth_user"."id" DESC LIMIT 10; args=()
Out[23]: [<User: hamdi>]
Answered By - hamdiakoguz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.