Categories
Python Answers

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

Spread the love

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,

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *