0Pricing
Django Academy · Урок

aggregate и annotate

Обобщайте целые наборы запросов или отдельные строки

«aggregate и annotate» — бесплатный урок Django Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Django Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Django Academy содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

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

Часто задаваемые вопросы

Урок «aggregate и annotate» бесплатный?

Да — полный текст урока «aggregate и annotate» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Django Academy, подпишись на CoddyKit PRO. Курс Django Academy содержит 4 уроков всего.

Чему я научусь в уроке «aggregate и annotate»?

Обобщайте целые наборы запросов или отдельные строки Ты практикуешь Django Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Django Academy?

Предыдущий опыт не требуется. Django Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «aggregate и annotate»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Django Academy?

Да. Каждый урок Django Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. aggregate и annotate
  2. Выражения F для атомарных обновлений
  3. Объекты Q для сложных фильтров
  4. Условная агрегация с Case/When
← Назад к Django Academy