aggregate frente a annotate
Resuma querysets completos o por fila
aggregate frente a annotate es una lección gratuita de Django Academy en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Django Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Django Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Two Ways to Summarize
The ORM gives you two summary tools: aggregate collapses a whole queryset into one result, while annotate adds a value to each row.
What aggregate Returns
Calling aggregate ends the query and hands you a plain Python dictionary, not a queryset, so there is nothing left to filter afterward.
from django.db.models import Avg
Book.objects.aggregate(Avg("price"))
# {"price__avg": 24.5}Naming Your Result
Pass a keyword to aggregate to name the output key yourself, which reads far better than the auto-generated price__avg label.
Book.objects.aggregate(avg_price=Avg("price"))
# {"avg_price": 24.5}Common Aggregate Functions
You get the usual SQL toolkit: Count, Sum, Avg, Min, and Max. Each one rolls the whole queryset down to a single number.
from django.db.models import Count, Sum
Book.objects.aggregate(total=Count("id"), revenue=Sum("price"))What annotate Returns
By contrast, annotate returns a queryset where every object carries a new computed attribute, so you can keep filtering and ordering.
Per-Row Counts
Use annotate with a related count to answer per-object questions, like how many books each author has written.
Author.objects.annotate(num_books=Count("book"))
# each author now has .num_booksGroup By Happens for You
When you annotate over a relation, Django adds the GROUP BY clause automatically, grouping by the model you started from.
Filter on an Annotation
Because annotate keeps a queryset, you can filter on the new value, for example to find authors with more than five books.
Author.objects.annotate(n=Count("book")).filter(n__gt=5)Order by an Annotation
You can also order_by a computed value, so ranking your busiest authors is a one-line query.
Author.objects.annotate(n=Count("book")).order_by("-n")Filter Before You Annotate
Order matters: a filter before annotate narrows which rows get counted, while a filter after it tests the computed result.
Pick the Right Tool
Ask one question: do you want a single summary for the whole set, or one value per object? That choice decides aggregate versus annotate.
Quick Check
You want each author's book count, kept as a queryset you can still order. Which call fits?
Recap
Remember the split: aggregate returns one summary dict and ends the query, while annotate adds a value per row and keeps a queryset you can filter and order. 🎯
Preguntas frecuentes
¿La lección «aggregate frente a annotate» es gratis?
Sí — el texto completo de «aggregate frente a annotate» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Django Academy, actualiza a CoddyKit PRO. El curso de Django Academy incluye 4 lecciones en total.
¿Qué aprenderé en «aggregate frente a annotate»?
Resuma querysets completos o por fila Practicas Django Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Django Academy?
No se requiere experiencia previa. Django Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.
¿Cuánto tiempo toma la lección «aggregate frente a annotate»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Django Academy?
Sí. Cada lección de Django Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- aggregate frente a annotate
- Expresiones F para actualizaciones atómicas
- Objetos Q para filtros complejos
- Agregación condicional con Case/When