Django ORM μμ μ§κ³ ν¨μμ κ·Έλ£Ήν(aggregate, group by)λ₯Ό μ¬μ©νλ λ°©λ²
Tip! μ§κ³ ν¨μ
- count() : NULLμ΄ μλ λ μ½λμ μ
- sum() : νλλͺ μ κ°λ€μ ν©κ³
- avg() : νλλͺ μ κ°λ€μ νκ·
- min() : νλλͺ μ κ° μ€ κ°μ₯ μμ κ°
- max() : νλλͺ μ κ° μ€ κ°μ₯ ν° κ°
μ°Έκ³ ! count()λ₯Ό μ μΈν μμΉλ₯Ό κ³μ°νλ μ§κ³ ν¨μλ NULL κ°μ κ°μ§ νμ λ°μ΄ν°λ 무μνκ³ κ³μ°
# μμ μ½λ
from django.db.models import Sum
OrderList.objects.aggregate(total_price=Sum('price'))
>>> {'total_price': 488000}
annotate
λ©μλλ₯Ό μ¬μ©<from django.db import F
# labelμ΄μ μ΄λ¦μ tagλ‘ λ³κ²½
Article.objects.all().annotate(tag=F("label"))
annotate
ν¨μλ‘ μ§κ³λ λ°μ΄ν°μμ μ§κ³ ν¨μλ₯Ό μ€ν κ°λ₯# μμ μ½λ
StudentGrade.objects
.filter(year=2020)
.values("class")
.annotate(student_count=Count("student_id"), score_average=Avg("score"))
.filter(student_count__gte=30)
.values("score_average")
μ§μ ν μ΄ λͺ
= μ§κ³ν¨μ(μ§κ³λ μ΄ λͺ
)
μΌλ‘ μ§μ Tip! μΆκ° λ΄μ©
Case
== if .. elif .. else
Case
μ Value
, When
Case
λ if elif else
λ λΉμ·νλ€κ³ λ³Ό μ μμdata = queryset.annotate(date=truncClass('date_joined'))
.values('date')
.annotate(active_num=Count(
Case(
When(
id__in=active_ids,
then="id",),),
distinct=True,
),
active_num=Count(
Case(
When(
id__in=more_active_ids,
then="id",),)
,distinct=True,
),
deactive_num=Count(
Case(
When(
id__in=deactive_ids,
then="id",),),
distinct=True,),)
.order_by('date')