Chartjs-Building chart using charjs in Django

0👍

try

data = invoice.objects.filter(invoice_date__year=2022).values('invoice_date__month').annotate(month_wise_count=Count('id')).order_by('invoice_date__month')

Then, while looping the data, do datum['month_wise_count'], or in template {{ datum.month_wise_count }}.

Please note that in practice, you should NOT use .filter(invoice_date__year=2022). Replace 2022 with a variable denoting current year.


UPDATE: Example models I use to test the queryset.

# models.py 
class invoice(models.Model):
    invoice_date = models.DateField()

Testing

# python3 manage.py shell

# Step 1: create some random invoices
from django.utils import timezone
from .models import invoice
import random

random.seed(0) # be reproducible

date_0 = timezone.localdate().replace(2022, 1, 1)
a_day = timezone.timedelta(days=1)


for i in range(1000):
    rand_date = date_0 + random.randint(0, 364) * a_day
    invoice(invoice_date=rand_date).save()

# Step 2. Run the queryset. 
data = invoice.objects\
    .values('invoice_date__month')\
    .annotate(month_wise_count=Count('id'))\
    .order_by('invoice_date__month')

for datum in data:
    print(f"{datum['invoice_date__month']:2}. {datum['month_wise_count']}")

This generates following result:

 1: 84
 2: 89
 3: 92
 4: 78
 5: 74
 6: 79
 7: 84
 8: 92
 9: 79
10: 70
11: 90
12: 89

Apologize: I made a mistake to put .order_by before .values. It should be at the end of queryset. It is now correct.

Leave a comment