2

I need to retrieve month name with sum total price of the corresponding month. Here is my order table sample

Database Sample

My try is:

month_wise_sales = Order.objects\
.annotate(month=ExtractMonth('created_at'))\
.values('month')\
.annotate(total_sales=Sum('total_price'))

It will return

<QuerySet [{'month': 7, 'total_sales': Decimal('138400.00')}, {'month': 9, 'total_sales': Decimal('1150.00')}]>

My desire is something like this

[{'month': July, 'total_sales': Decimal('138400.00')}, {'month': September, 'total_sales': Decimal('1150.00')}]

How to resolve this?

shafik
  • 6,098
  • 5
  • 32
  • 50

1 Answers1

0

This work fine for me. Working query

month_wise_sales = Order.objects\
.annotate(month=Cast('created_at', DateField()))\
.values('month')\
.annotate(total_sales=Sum('total_price'))

and then in template use this

{{ monthly_sales.month | date:"M"}}

By this, I will get the sum of total price with month name.

shafik
  • 6,098
  • 5
  • 32
  • 50