0Pricing
Django Academy · Lezione

aggregate o annotate

Riepilogare interi queryset o singole righe

aggregate o annotate è una lezione Django Academy gratuita su CoddyKit. Questa è la lezione 1 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Django Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Django Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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_books

Group 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. 🎯

Domande Frequenti

La lezione «aggregate o annotate» è gratuita?

Sì — il testo completo di «aggregate o annotate» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Django Academy, passa a CoddyKit PRO. Il corso Django Academy include 4 lezioni in totale.

Cosa imparerò in «aggregate o annotate»?

Riepilogare interi queryset o singole righe Eserciti Django Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Django Academy?

Non è richiesta alcuna esperienza precedente. Django Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 1 di 4.

Quanto tempo richiede la lezione «aggregate o annotate»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Django Academy?

Sì. Ogni lezione Django Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. aggregate o annotate
  2. Espressioni F per aggiornamenti atomici
  3. Oggetti Q per filtri complessi
  4. Aggregazione condizionale con Case/When
← Torna a Django Academy