Case/When을 사용한 조건부 집계
단일 쿼리 안에서 분기 로직을 작성합니다
Case/When을 사용한 조건부 집계은(는) CoddyKit의 무료 Django Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Django Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Django Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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, ValueA 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. 📊
자주 묻는 질문
“Case/When을 사용한 조건부 집계” 강의는 무료인가요?
네 — “Case/When을 사용한 조건부 집계” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Django Academy 강의 전체를 잠금 해제할 수 있습니다. Django Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“Case/When을 사용한 조건부 집계”에서 뭘 배우나요?
단일 쿼리 안에서 분기 로직을 작성합니다 브라우저에서 직접 실행하는 실습 코드로 Django Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Django Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Django Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“Case/When을 사용한 조건부 집계” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Django Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Django Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- aggregate와 annotate 비교
- 원자적 업데이트를 위한 F 표현식
- 복잡한 필터를 위한 Q 객체
- Case/When을 사용한 조건부 집계