Aggregation (Grouping data)

aggregate()

“Aggregate calculates values for the entire queryset”

전체 queryset에 대한 값을 계산

특정 필드 전체의 합, 평균, 개수 등을 계산할 때 사용

딕셔너리를 반환

 

 

Aggregation functions

Avg, Count, Max, Min, Sum등

 

 

Avg

# shell_plus에서는 import 하지 않아도 된다.
from django.db.models import Avg

User.objects.filter(age__gte=30).aggregate(Avg('age')) 
=> {'age__avg': 37.6590909090909091}

# 딕셔너리 key 이름을 수정 할 수도 있다.
User.objects.filter(age__gte=30).aggregate(avg_value=Avg('age')) 
=> {'age_values=': 37.6590909090909091}

나이가 30살 이상인 사람들의 평균 나이 조회하기

 

Max

from django.db.models import Max

User.objects.aggregate(Max('balance'))
=> {'balance__max' : 1000000}

가장 높은 계좌 잔액 조회하기

 

 

 

 

Sum

from django.db.models import Max

User.objects.aggregate(Sum('balance'))
=> {'balance__sum' : 1443540}

모든 계좌 잔액 총액 조회하기

 

 

 

annotate()

쿼리의 각 항목에 대한 요약 값을 계산

SQL의 GROUP BY 에 해당

‘주석을 달다’라는 사전적 의미를 가지고 있음

 

 

 

from django.db.modles import Count

User.objects.values('country').annotate(Count('country'))
=> <QuerySet [{'country':'강원도', 'country__count':14}, {'country':'경기도', 'country__count':9}, {'country':'경상남도', 'country__count':8}...>

 

# aggregate와 마찬가지로 딕셔너리의 key값 변경할 수 있다.
User.objects.values('country').annotate(num_of_country=Count('country'))
=> <QuerySet [{'country':'강원도', 'num_of_country':14}, {'country':'경기도', 'num_of_country':9}, {'country':'경상남도', 'num_of_country':8}...>

 

각 지역별로 몇 명씩 살고 있는지 조회하기

 

 

 

User.objects.values('country').annotate(num_of_country=Count('country'), avg_balance=Avg('balance'))

각 지역별로 몇 명씩 살고 있는지 + 지역별 계좌 잔액 평균 조회하기

 

한번에 여러 값을 계산해서 조회할 수 있다.

 

 

 

Article.objects.annotate(
	number_of_comment=Count('comment'),
    pub_date=Count('comment',filter=Q(comment__created_at__lte='2000-01-01'))
    )

comment-article 관계가 N:1일 경우 이와 같은 참조도 가능하다.

전체 게시글을 조회하면서 annotate로 각게시글의 댓글 개수(number_of_comment)와 2000-01-01보다 나중에 작성된 댓글의 개수(pub_date)를 함께 조회 했다.