Menu Close

How to group by date (day, month, year) with Python Django?

To group by date (day, month, year) with Python Django, we can use the values method.

For instance, we write

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

Sales.objects
    .annotate(month=TruncMonth('created')) 
    .values('month')                        
    .annotate(c=Count('id'))                
    .values('month', 'c')              

to call values with 'month' to group by month in our query,

Posted in Python, Python Answers