TIL78. Django ORM : Aggregate

ID์งฑ์žฌยท2021๋…„ 11์›” 8์ผ
1

Django ORM

๋ชฉ๋ก ๋ณด๊ธฐ
4/7
post-thumbnail

๐Ÿ“Œ ์ด ํฌ์ŠคํŒ…์—์„œ๋Š” Django ORM์˜ Aggregate ๋งค์„œ๋“œ์— ๋Œ€ํ•ด ์ •๋ฆฌํ•˜์˜€์Šต๋‹ˆ๋‹ค.



๐ŸŒˆ Aggregate


๐Ÿค” Aggregate๋ž€ ๋ฌด์—‡์ผ๊นŒ?

โœ”๏ธ ์žฅ๊ณ  ORM์„ ์ด์šฉํ•ด ๊ฐ์ฒด๋ฅผ CRUD(์ƒ์„ฑ,์กฐํšŒ,์ˆ˜์ •,์‚ญ์ œ)ํ•  ์ˆ˜ ์žˆ์ง€๋งŒ, ๋•Œ๋กœ๋Š” ํ•ญ๋ชฉ๋“ค์˜ ์ง‘๊ณ„๊ฐ’์„ ๊ตฌํ•ด์•ผํ•  ๋•Œ๊ฐ€ ์žˆ๋‹ค.

โœ”๏ธ aggregate๋Š” Max, Min, Avg, Sum ๋“ฑ์˜ ํ•จ์ˆ˜๋ฅผ ์ œ๊ณตํ•จ์œผ๋กœ์จ ๊ธฐ๋ก๋œ ํ•ญ๋ชฉ์˜ ์ง‘๊ณ„๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ๋„๋ก ๋„์™€์ค€๋‹ค.

โœ”๏ธ annote์˜ ์‚ฌ์ „์  ์˜๋ฏธ๋Š” '์ฃผ์„์„ ๋‹ฌ๋‹ค'๋ž€ ์˜๋ฏธ์ด์ง€๋งŒ, django orm์—์„œ๋Š” field(column)๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค ์ •๋„๋กœ ์ดํ•ดํ•˜๋ฉด ๋œ๋‹ค. ํ•ญ๋ชฉ์˜ ์ง‘๊ณ„๋ฅผ ๊ตฌํ•ด ์‹ค์ œ ์กด์žฌํ•˜์ง€ ์•Š๋Š” ๊ฐ€์ƒ์˜ field์— ๊ธฐ๋กํ•ด ๋‘๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

๐Ÿค” Aggregate๋Š” ์–ด๋–ป๊ฒŒ ์‚ฌ์šฉํ• ๊นŒ?

โœ”๏ธ aggregate๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” django.db.models์—์„œ ์ง‘๊ณ„๋ฅผ ์œ„ํ•œ ํ•จ์ˆ˜๋ฅผ importํ•ด์•ผ ํ•œ๋‹ค.

Django Shell >>> from django.db.models import Avg, Max, Min, Sum, Count

โœ”๏ธ Avg๋ฅผ ํ‰๊ท , Max๋Š” ์ตœ๋Œ€๊ฐ’, Min์€ ์ตœ์†Œ๊ฐ’, Sum์€ ํ•ฉ๊ณ„, Count๋Š” ๊ฐฏ์ˆ˜๋ฅผ ๊ตฌํ•ด์ค€๋‹ค.

Django Shell >>>  User.objects.all().aggregate(Avg('age')) 
# {'age__avg': 28.391938481}
Django Shell >>>  User.objects.all().aggregate(Max('age')) 
# {'age__avg': 42}
Django Shell >>>  User.objects.all().aggregate(Min('age')) 
# {'age__avg': 26}
Django Shell >>>  User.objects.all().aggregate(Sum('age')) 
# {'age__avg': 872}
Django Shell >>>  User.objects.all().aggregate(Count('id')) 
# {'id__Count': 32}

โœ”๏ธ aggregate๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด "ํ•„๋“œ๋ช…_์ง‘๊ณ„๋ฐฉ์‹"์„ ํ†ตํ•ด ์ž๋™์œผ๋กœ ํ•„๋“œ๊ฐ’์„ ์ƒ์„ฑํ•ด์ค€๋‹ค.

โœ”๏ธ ์ด๋ฅผ ์ง€์ •ํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด, ์›ํ•˜๋Š” alias๋กœ ๋ฐ›์•„์ฃผ๋ฉด ๋œ๋‹ค. ์•„๋ž˜๋Š” ์ „์ฒด ํ‰๊ท  ํ‰์ ์„ ๊ตฌํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค. ratingํ•„๋“œ๋ฅผ ์‚ฌ์šฉํ•ด ์—ญ์ฐธ์กฐํ•˜์—ฌ ๋ชจ๋“  ํ‰์ ์„ ๊ฐ€์ ธ์™€ ํ‰๊ท ์„ ๊ตฌํ•ด์ค€๋‹ค.

Django Shell >>> q = Movie.objects.all().annotate(average_point=Avg("rating__rate"))
Django Shell >>> q
# {'average__point': Decimal('3.61429')}

โœ”๏ธ 1๋ฒˆ ์˜ํ™”์— ์ฃผ์–ด์ง„ ํ‰์ ๋“ค์„ ๊ฐ€์ ธ์™€ ํ‰๊ท ์„ ๊ตฌํ•˜๋Š” ๋ฐฉ์‹์€ ์•„๋Œ€์™€ ๊ฐ™๋‹ค.

Django Shell >>> q = Movie.objects.get(id=1).annotate(average_point=Avg("rating__rate"))
Django Shell >>> q
# {'average__point': Decimal('5.19231')}
profile
Keep Going, Keep Coding!

0๊ฐœ์˜ ๋Œ“๊ธ€