0Pricing
Django Academy · Lezione

Aggregazione condizionale con Case/When

Gestire la logica condizionale all'interno di una singola query

Aggregazione condizionale con Case/When è una lezione Django Academy gratuita su CoddyKit. Questa è la lezione 4 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.

Branching Inside a Query

Sometimes you need different results for different rows. Case lets the database choose a value per row, like an if statement in SQL.

The Case and When Pair

A Case holds one or more When branches; each When pairs a condition with the value to use when that condition is true.

from django.db.models import Case, When, Value

A Simple Label

Annotate a computed label by giving each When a condition and a then value, with a default for the rest.

Book.objects.annotate(tier=Case(
  When(price__gte=50, then=Value("premium")),
  default=Value("standard")))

Why Conditional Aggregation

The real power comes from putting Case inside an aggregate, so you can count or sum only the rows that match a condition.

Count Rows That Match

Wrap a Case in Count to tally just the matching rows, since non-matching branches return null and are skipped.

Count(Case(When(active=True, then=1)))

The filter= Shortcut

Modern Django offers a cleaner way: pass filter to an aggregate to count or sum a subset without writing Case yourself.

Count("id", filter=Q(active=True))

Multiple Buckets at Once

Annotate several conditional aggregates together to build a breakdown, like active and inactive counts in one query.

Team.objects.annotate(
  active=Count("member", filter=Q(member__active=True)),
  inactive=Count("member", filter=Q(member__active=False)))

Sum a Subset

The same trick works with Sum, letting you total only the rows that pass a condition, such as paid invoices.

Sum("amount", filter=Q(status="paid"))

Set an output_field

When the value types are not obvious, give Case an output_field so Django knows how to handle the result.

Case(When(...), default=Value(0), output_field=IntegerField())

Order by a Case

You can even order_by a Case annotation to create custom sort priorities that plain field ordering cannot express.

One Trip to the Database

All of this branching runs server-side in a single query, far faster than looping in Python and counting by hand.

Quick Check

You want one number: how many members of a team are active, computed in the database.

Recap

Case and When add per-row branching, and pairing conditions with aggregates, or the filter= shortcut, builds rich breakdowns in one query. 📊

Domande Frequenti

La lezione «Aggregazione condizionale con Case/When» è gratuita?

Sì — il testo completo di «Aggregazione condizionale con Case/When» è 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 «Aggregazione condizionale con Case/When»?

Gestire la logica condizionale all'interno di una singola query 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 4 di 4.

Quanto tempo richiede la lezione «Aggregazione condizionale con Case/When»?

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