Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Query set for counting records each month

class Orders(models.Model):
  orderid = models.IntegerField(db_column='orderID', primary_key=True) 
  pickupdate = models.DateField(db_column='pickupDate', blank=True, null=True)  

I want to display total records in the Model for each month. The solution that I have found require me to enter year

Orders.objects.filter(pickupdate__year = '2006').values_list('pickupdate__month').annotate(total = Count('orderid')

The results from the queryset above are like this :

<QuerySet [(1, 31), (2, 27), (3, 31), (4, 30), (5, 31), (6, 29), (7, 30), (8, 31), (9, 30), (10, 31), (11, 30),
 (12, 31)]>

I want that the queryset able to get the monthly range automatically from the database,without the need to put year to the queryset

The data that I want to display is like this :

Month        | Total 
January 2007 | 1
February 2007| 2
etc


enter code here
like image 300
user43944 Avatar asked Dec 10 '22 05:12

user43944


1 Answers

Use TruncMonth db function to extract the month from the date field

Do something like this,

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

Orders.objects.annotate(month=TruncMonth('pickupdate')).values('month').annotate(total=Count('orderid'))


This ORM will generate a SQL query as,

SELECT django_date_trunc('month', "sample_orders"."pickupDate") AS "month", COUNT("sample_orders"."orderID") AS "total" FROM "sample_orders" GROUP BY django_date_trunc('month', "sample_orders"."pickupDate")



EXAMPLE

In [8]: from django.db.models import Count

In [9]: from django.db.models.functions import TruncMonth

In [10]: Orders.objects.annotate(month=TruncMonth('pickupdate')).values('month').annotate(total=Count('orderid'))
Out[10]: <QuerySet [{'month': datetime.date(2018, 8, 1), 'total': 2}, {'month': datetime.date(2018, 9, 1), 'total': 4}]>
like image 145
JPG Avatar answered Dec 12 '22 17:12

JPG