I am trying to get/count how many orders that were made in a month and return it as a response to the api view, i have written some logic to do this, but the issue is this: It does not count how many total orders were made in a month, but instead add new orders for the same month.
To be more explicit, look at the reponse below:
This is the query i wrote to get and count the orders based on the months
from django.db.models.functions import ExtractMonth
orders = Orders.objects.annotate(month=ExtractMonth("date")).values("month").annotate(count=Count("id")).values("month", "count")
print("orders", orders)
This is th response
"orders": [
{
"month": 1, #january
"count": 1 #one order
},
{
"month": 1, #january
"count": 1 #one order
},
{
"month": 3, #march
"count": 1 #one order
},
{
"month": 3, #march
"count": 1 #one order
},
{
"month": 4, #April
"count": 1 # one order
},
{
"month": 4,
"count": 1
}
]
Look at the first month januray, i want it to return the response like this
{
"month": 1, # january
"count": 2 # two orders
},
I also have this logic where i loop through the orders
then append the month
and total_orders
to the variable
Complete Code
from django.db.models import Count, Avg
from django.db.models.functions import ExtractMonth
import calendar
@api_view(('GET', ))
def ChartAPIFBV(request):
orders = Orders.objects.annotate(month=ExtractMonth('date'
)).values('month').annotate(count=Count('id'
)).values('month', 'count')
month = []
total_orders = []
for i in orders:
month.append(calendar.month_name[i['month']])
total_orders.append(i['count'])
data = {'month': month, 'total_orders': total_orders,
'orders': orders}
return Response(data)
Complete Respose
{
"month": [
"January",
"January",
"March",
"March",
"March",
"March",
"April",
"April"
],
"total_orders": [
1,
1,
1,
1,
1,
1,
1,
1
],
"orders": [
{
"month": 1,
"count": 1
},
{
"month": 1,
"count": 1
},
{
"month": 3,
"count": 1
},
{
"month": 3,
"count": 1
},
{
"month": 3,
"count": 1
},
{
"month": 3,
"count": 1
},
{
"month": 4,
"count": 1
},
{
"month": 4,
"count": 1
}
]
}