Чтобы добавить, в качестве альтернативы для использования extra()
: начиная с Django 1.8, вы также можете использовать условные выражения.
>>> year_overview = Link.objects.filter(pub_date__year=year).aggregate(
jan=Sum(
Case(When(created__month=0, then=1),
output_field=IntegerField())
),
feb=Sum(
Case(When(created__month=1, then=1),
output_field=IntegerField())
),
mar=Sum(
Case(When(created__month=2, then=1),
output_field=IntegerField())
),
apr=Sum(
Case(When(created__month=3, then=1),
output_field=IntegerField())
),
may=Sum(
Case(When(created__month=4, then=1),
output_field=IntegerField())
),
jun=Sum(
Case(When(created__month=5, then=1),
output_field=IntegerField())
),
jul=Sum(
Case(When(created__month=6, then=1),
output_field=IntegerField())
),
aug=Sum(
Case(When(created__month=7, then=1),
output_field=IntegerField())
),
sep=Sum(
Case(When(created__month=8, then=1),
output_field=IntegerField())
),
oct=Sum(
Case(When(created__month=9, then=1),
output_field=IntegerField())
),
nov=Sum(
Case(When(created__month=10, then=1),
output_field=IntegerField())
),
dec=Sum(
Case(When(created__month=11, then=1),
output_field=IntegerField())
),
)
>>> year_overview
{'mar': None, 'feb': None, 'aug': None, 'sep': 95, 'apr': 1, 'jun': None, 'jul': None, 'jan': None, 'may': None, 'nov': 87, 'dec': 94, 'oct': 100}