class Transactions(models.Model):
TRANSACTION_TYPE_CHOICES = (
('income', 'Income'),
('expense', 'Expense'),
)
PAYMENT_MODE_CHOICES = (
('cash', 'Cash'),
('enbd', 'ENBD'),
('nol', 'NOL'),
('sib', 'SIB'),
)
trans_id = models.AutoField(primary_key=True)
trans_date = models.DateField(verbose_name="Date")
trans_type = models.CharField(max_length=10, choices=TRANSACTION_TYPE_CHOICES, verbose_name="Type")
trans_details = models.ForeignKey(Details, on_delete=models.CASCADE, verbose_name="Details", related_name="trnsactions")
trans_category = models.ForeignKey(MasterCategory, on_delete=models.CASCADE, verbose_name="Category", related_name="transactions")
trans_mode = models.CharField(max_length=10, choices=PAYMENT_MODE_CHOICES, verbose_name="Payment Mode")
trans_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="Amount")
objects = models.Manager()
class Meta:
verbose_name_plural = "Transactions"
def __str__(self):
return f"{self.trans_id} - {self.trans_type} - {self.trans_details} - {self.trans_category} - {self.trans_amount}"
above is my model, and below is my view
def by_mode(request):
all_modes = dict(Transactions.PAYMENT_MODE_CHOICES).keys()
totals = Transactions.objects.annotate(
month=TruncMonth('trans_date'),
mode=F('trans_mode')
).values('month', 'mode').annotate(
total=Sum('trans_amount')
)
data = {}
for total in totals:
month = total['month'].strftime('%B')
mode = total['mode']
if mode not in data:
data[mode] = {}
data[mode][month] = total['total']
return render(request, 'by_mode.html', {'data': data, 'modes': all_modes})
below is my template
{% extends 'base.html' %}
{% block content %}
<h1>Transactions by Payment Mode</h1>
<table class="table">
<thead>
<tr>
<th>Month</th>
{% for mode in modes %}
<th>{{ mode|title }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for month, mode_totals in data.items %}
<tr>
<td>{{ month }}</td>
{% for mode in modes %}
<td>{{ mode_totals }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
I want to display a report on every month as a table
horizontal should have months and vertical should have trans_mode.