[Answered ]-How to count and make addition with for loop with a table in Django?

1👍


Try this,

from django.db.models import Count, Sum

Customer.objects.values("country", "country__name", "country__alpha_2").annotate(
    **{
        f"{stored.lower().replace(' ', '_')}_count": Count(
            "risk_rating", filter=Q(risk_rating=stored)
        )
        for (stored, displayed) in Customer.RISK_RATING
    },
    total_credit_limit=Sum("credit_limit"),
).order_by("country").distinct("country")

This will yield objects with the following fields,

["country id", "country name", "country codes i.e. alpha_2", "low_risk_count", "medium_risk_count", …, "total_credit_limit"]

Update #1:

To access it in the template, use something like this.

<table>
<tr>
    <th>Country</th>
    <th>Total Customers</th>
    <th>Low Risk</th>
    <th>Medium Risk</th>
    <th>Moderate High Risk</th>
    <th>...</th>
    <th>Total Credit Limit</th>
</tr>
{% for country in countries %}
    <tr>
        <td>{{ country.country__name }}</td>
        <td>{{ country.total_customers }}</td>
        <td>{{ country.low_risk_count }}</td>
        <td>{{ country.medium_risk_count }}</td>
        <td>{{ country.moderate_high_risk_count }}</td>
        <td>{{ country.... }}</td>
        <td>{{ country.total_credit_limit }}</td>
    </tr>
{% endfor %}
</table>

Update #2:

from django.db.models import Count, Sum

Customer.objects.values("country", "country__name", "country__alpha_2").annotate(
    **{
        f"{stored.lower().replace(' ', '_')}_count": Count(
            "risk_rating", filter=Q(risk_rating=stored)
        )
        for (stored, displayed) in Customer.RISK_RATING
    },
    total_credit_limit=Sum("credit_limit"),
    total_customers=Count("id")
).order_by("country").distinct("country")

Leave a comment