Django - 限制查询结果 [英] Django - limiting query results
本文介绍了Django - 限制查询结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要使用模型的最后10个实例,并具有以下代码:
I want to take the last 10 instances of a model and have this code:
Model.objects.all().order_by('-id')[:10]
,然后只需要10个最后一个?
有没有更有效的方法?
Is it true that firstly pick up all instances, and then take only 10 last ones? Is there any more effective method?
推荐答案
Django查询器是懒惰的。这意味着只有当您特别要求结果时,查询才会触发数据库。
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.
如下所示,您的代码只执行一个sql查询以仅获取最后10个项目。
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>]
这篇关于Django - 限制查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文