1👍
Since you need to display the total sales for each day of the week and not a particular day as you mentioned in the comments above, you can do the following:
class TrafficListView(ListView):
model = Traffic
template_name = 'dashboard/pages/traffic.html'
def get_context_data(self, **kwargs):
context = super(TrafficListView, self).get_context_data(**kwargs)
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday','Sunday'] # days of the week
total_sales = {} # create an empty dictionary
for day in days:
# get the sales for that particular day
total_sales[day] = Traffic.objects.filter(day_of_week=day).aggregate(Sum('sales')).get('sales__sum', 0.00)
context['total_sales'] = total_sales # pass 'total_sales' dictionary in context
return context
Here, we create a list days
having values from Monday
to Sunday
. Then we create an empty dictionary total_sales
.
We will now iterate through the days
list and filter all the objects from Traffic
model where day_of_week
is equal to that particular day.
lets say Monday
. Then we perform Sum
aggregation on the objects returned for day_of_week
as Monday
on the sales
field. The value returned from sales_sum
is stored in a key Monday
in the total_sales
dictionary. So, after iteration is complete, there will be 7 keys in the total_sales
for each day of the week with the value being the sum of sales for that particular day.
In your template, use {{total_sales.Monday}}
to access Monday
sales, {{total_sales.Tuesday}}
for Tuesday
sales and so on.