order_by, Recortes e Avaliação Preguiçosa
Ordene, limite e entenda quando as consultas acessam o DB
order_by, Recortes e Avaliação Preguiçosa é uma aula grátis de Django Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Django Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Django Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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. ⚡
Perguntas Frequentes
A aula “order_by, Recortes e Avaliação Preguiçosa” é grátis?
Sim — o texto completo de “order_by, Recortes e Avaliação Preguiçosa” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Django Academy, atualize para CoddyKit PRO. O curso de Django Academy inclui 4 aulas no total.
O que vou aprender em “order_by, Recortes e Avaliação Preguiçosa”?
Ordene, limite e entenda quando as consultas acessam o DB Você pratica Django Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Django Academy?
Nenhuma experiência prévia é necessária. Django Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “order_by, Recortes e Avaliação Preguiçosa”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Django Academy?
Sim. Cada aula de Django Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- all(), get() e filter()
- Consultas de Campo e exclude()
- order_by, Recortes e Avaliação Preguiçosa
- values, values_list e count