728x90
from django.db.models import Avg, Max, Sum, Count
# 전체 평균 나이
User.objects.aggregate(Avg('age'))
# 김씨의 평균 나이
User.objects.filter(last_name='김').aggregate(Avg('age'))
# 강원도에 사는 사람의 평균 계좌 잔고
User.objects.filter(country='강원도').aggregate(Avg('balance'))
# 계좌 잔액 중 가장 높은 값
User.objects.aggregate(Max('balance'))
# 계좌 잔액 총액
User.objects.aggregate(Sum('balance'))
- Annotate
- '주석을 달다' 라는 사전적 의미
- 필드를 하나 만들고 거기에 '어떤 내용'을 채워 넣는다.
- 데이터베이스에 영향을 주지 않고, Queryset에 컬럼 하나를 추가하는 것과 같다.
from django.db.models import Count
# 지역별 인원 수
User.objects.values('country').annotate(Count('country'))
# <QuerySet [{'country': '강원도', 'country__count': 14}, ...
User.objects.values('country').annotate(num_countries=Count('country'))
# <QuerySet [{'country': '강원도', 'num_countries': 14}, ...
User.objects.values('country').annotate(Count('country'), avg_balance=Avg('balance'))
# <QuerySet [{'country': '강원도', 'country__count': 14, 'avg_balance': 157895.0}, ...
728x90
반응형
'TIL - 프로그래밍 > 개념, 설정' 카테고리의 다른 글
[Python] User (0) | 2022.04.18 |
---|---|
[Python] 외부 키, 참조 (0) | 2022.04.17 |
[Python] 데이터베이스 (0) | 2022.04.15 |
[Python] Tree3 - heap (0) | 2022.04.05 |
[Python] Tree2 (0) | 2022.04.04 |
댓글