django orm group by month and year

To group Django ORM queryset by month and year, you can follow these steps:

Step 1: Import the necessary modules Make sure to import the required modules for working with Django ORM and date-related operations:

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

Step 2: Perform the grouping To group the queryset by month and year, you can use the annotate() function along with the ExtractMonth and ExtractYear functions. Here's an example:

queryset = YourModel.objects.annotate(
    month=ExtractMonth('date_field'),
    year=ExtractYear('date_field')
).values('month', 'year').annotate(count=Count('id'))

In the above code, replace YourModel with the name of your Django model, and date_field with the name of the field you want to group by.

Step 3: Access the grouped data The grouped data will be returned as a queryset, which you can iterate over or access the values as needed. For example, you can print the month, year, and count for each group:

for data in queryset:
    month = data['month']
    year = data['year']
    count = data['count']
    print(f"Month: {month}, Year: {year}, Count: {count}")

This will print the month, year, and count for each group in the queryset.

By following these steps, you can group a Django ORM queryset by month and year.