To display the required information in HTML tables using Django's template system, you can follow these steps:
- Retrieve the data from the database:
from django.db.models import Count, Sum
# Step 1: Retrieve the data from the database
customers = Customer.objects.all().annotate(
order_count=Count('order', distinct=True),
order_sum=Sum('order__value')
).order_by('city')
cities = customers.values('city').annotate(
customer_count=Count('id'),
order_sum=Sum('order__value')
).order_by('city')
- Pass the data to the template context:
from django.shortcuts import render # Step 2: Pass the data to the template context context = { 'cities': cities, 'customers': customers } return render(request, 'your_template.html', context)
- Iterate over the data in the HTML template:
<!-- Step 3: Iterate over the data in the HTML template -->
<!-- Display Count of Customers from each City -->
<table>
<thead>
<tr>
<th>City</th>
<th>Customer Count</th>
</tr>
</thead>
<tbody>
{% for city in cities %}
<tr>
<td>{{ city.city }}</td>
<td>{{ city.customer_count }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<!-- Display Total value of Orders from each City -->
<table>
<thead>
<tr>
<th>City</th>
<th>Order Value Sum</th>
</tr>
</thead>
<tbody>
{% for city in cities %}
<tr>
<td>{{ city.city }}</td>
<td>{{ city.order_sum }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<!-- Display Count of Orders from each Customer -->
<table>
<thead>
<tr>
<th>Customer</th>
<th>Order Count</th>
</tr>
</thead>
<tbody>
{% for customer in customers %}
<tr>
<td>{{ customer.name }}</td>
<td>{{ customer.order_count }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<!-- Display Total Sum of Orders from each Customer -->
<table>
<thead>
<tr>
<th>Customer</th>
<th>Order Sum</th>
</tr>
</thead>
<tbody>
{% for customer in customers %}
<tr>
<td>{{ customer.name }}</td>
<td>{{ customer.order_sum }}</td>
</tr>
{% endfor %}
</tbody>
</table>
Make sure to replace 'your_template.html' with the actual template file name where you want to display this data.