[Django]-Django Group Entries by Month

2👍

You can use TruncMonth [Django-doc] to truncate the ts_create to the start of a month, and then annotate with the number of items with:

from django.db.models import Count
from django.db.models.functions import TruncMonth

Data.objects.values(
    month=TruncMonth('ts_create')
).annotate(
    count=Count('pk')
).order_by('month')

This will produce a QuerySet of dictionaries with month and count as keys, like:

<QuerySet [
    {'month': date(2022, 1, 1), 'count': 14},
    {'month': date(2022, 2, 1), 'count': 25},
    {'month': date(2022, 3, 1), 'count': 13},
    {'month': date(2022, 4, 1), 'count': 2}
]>

0👍

Try this:

from django.db.models.functions import ExtractMonth, ExtractYear

test = Data.active_objects.annotate(year=ExtractYear('ts_create'),
                                month = ExtractMonth('ts_create')).values('year','month').annotate(total=Count('id'))

Leave a comment