order_by、切片与惰性求值
排序、限制结果,并了解查询何时访问 DB
order_by、切片与惰性求值 是 CoddyKit 上的免费 Django Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Django Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Django Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Put Rows in Order
Database rows have no guaranteed order. Call order_by() to sort a QuerySet by any field you choose.
Book.objects.order_by("title")Sort Descending
Put a minus sign in front of a field name to reverse the order, so the largest or newest value comes first.
Book.objects.order_by("-year")Sort by Several Fields
Pass multiple fields to order_by() and Django sorts by the first, then breaks ties with the next.
Book.objects.order_by("author", "-year")Take the Top Few
Slicing a QuerySet with Python syntax limits how many rows you fetch, perfect for a top-five list.
Book.objects.order_by("-year")[:5]Slice a Window
Give slicing a start and stop to grab a middle chunk. Django turns it into LIMIT and OFFSET for you. ✂️
Book.objects.all()[10:20]No Negative Slicing
You cannot use a negative index on a QuerySet. To get the last rows, reverse the order first, then slice.
Book.objects.order_by("-id")[:1]Queries Are Lazy
Building a QuerySet does not touch the database. Django stays lazy and waits until you really need the data.
qs = Book.objects.filter(published=True)What Triggers a Query
Evaluation happens when you loop, call list(), or check the length. That moment is when SQL finally runs.
for book in qs:
print(book.title)Build Now, Run Later
Laziness lets you chain filters across many lines, and Django still sends just one combined query at the end.
qs = Book.objects.filter(year__gte=2020).order_by("title")Caching the Results
Once a QuerySet is evaluated, Django caches the rows. Reusing the same variable avoids hitting the database twice.
Slicing Stays Lazy
An unevaluated slice is still lazy, so the LIMIT is added to the SQL instead of trimming rows in Python.
top = Book.objects.order_by("-year")[:3]Quick Check
You build a filtered QuerySet but never loop or list it. When does the SQL run?
Recap
You did it! order_by() sorts, slicing limits rows in SQL, and lazy evaluation means queries run only when used. ⚡
常见问题解答
「order_by、切片与惰性求值」课时是免费的吗?
是的 — 「order_by、切片与惰性求值」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Django Academy 课程的其余内容,请升级到 CoddyKit PRO。 Django Academy 课程共包含 4 节课。
「order_by、切片与惰性求值」这节课中我会学到什么?
排序、限制结果,并了解查询何时访问 DB 你通过在浏览器中直接运行的动手代码来练习 Django Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Django Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Django Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「order_by、切片与惰性求值」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Django Academy 课中编写并运行代码吗?
能。每节 Django Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- all()、get() 与 filter()
- 字段查询与 exclude()
- order_by、切片与惰性求值
- values、values_list 与 count