Sum total by date

44 views
Skip to first unread message

linsa...@gmail.com

unread,
Mar 1, 2021, 7:16:50 PM3/1/21
to Django users

My Model

class Expense(models.Model):
    date = models.DateField("Date", default=now)
    department =  models.CharField( max_length=200)
    #employee = models.ForeignKey(to=User, on_delete=models.CASCADE)
    employee = models.CharField( max_length=200)
    transactionId = models.CharField(max_length=200, unique=True)
    institutions = models.CharField( max_length=200)
    description = models.TextField(max_length=200)
    amount = models.FloatField()
    account_dr =  models.CharField( max_length=200)
    account_cr =  models.CharField( max_length=200)


The normal display of Transactions but i want a summary for each date like the table below and how to represent it on the html template
Capture.PNG
This is the result i want to achieve
Capture1.PNG

Lorenzo Prodon

unread,
Mar 8, 2021, 9:28:59 AM3/8/21
to Django users
CODE NOT TESTED
You can do this in the get_context_data method, in the view:
from django.db.models import Sum

chart_data = {}
for date in Expense.objects.all().distinct('date').values_list('date', flat=True):
  chart_data[date] = Expense.objects.filter(date=date).aggregate(Sum('amount'))['total__sum']
context['chart_data'] = chart_data

and this in the related template:
{% for key, value in chart_data.items %}
  <tr>
    <td>{{ key }}</td>
    <td>{{ value }}</td>
  </tr>
{% endfor %}
Reply all
Reply to author
Forward
0 new messages