I am a novice in python Django framework and I wish someone should please help on some piece of code I have been struggling with hours. I have an Expenditure Model with date and amount Fields among others, and I want to calculate total amount for the current month and display in django template through the views using the context dictionary. Here is my Expenditure model code:
class Expenditure(models.Model):
amount = models.PositiveIntegerField(null=False)
date = models.DateField(auto_now_add=False, auto_now=False, null=False)
Views.py codes here:
from django.db.models import Count, Sum
from django.db import connection
def index(request):
truncate_month = connection.ops.date_trunc_sql('month','day')
total_income = Income.objects.extra({'month': truncate_month}).values('date').annotate(Sum('amount'))
context = {
'total_income':total_income,
}
return render(request, 'dashboard/index.html', context)
This is how I am trying to display the Sum Total of amount for the current month and year in Django template.
{% for income in total_income %}
{{income.date}}{{income.amount}}
{% endfor %}
The result of my code above is displaying the months of dates from the Expenditure Model on the template whereas this is the only Output Result I am expecting: 'Aug. 2021: 13,000' Only Because August is the only current Month in 2021. Your kind assistance would help a lot. Thanks