[Answered ]-Django – Divide result of queryset by integer

1πŸ‘

βœ…

To divide, use widthratio template tag

# views.py

def projection(request):
    divider = int(date.today().strftime("%d"))
    qs = ManagerialRevenue.objects.values("accountplan__name").annotate(Sum("amount"))

    return render(
        request,
        "app/pages/planning/projection.html",
        context={"qs": qs, "divider": divider},
    )



# template.html

{% for item in qs %}
    {{ item.accountplan__name }}
    {{ item.amount__sum }}
    {% widthratio item.amount__sum divider 1 %}{{ item.amount__sum }}
{% endfor %}

Or, you can even update the qs variable in a way that hold the division result

views.py

def projection(request):
    divider = int(date.today().strftime("%d"))
    qs = ManagerialRevenue.objects.values("accountplan__name").annotate(Sum("amount"))
    qs_updated = [{**item, "div_result": item["amount__sum"] / divider} for item in qs]
    return render(
        request,
        "app/pages/planning/projection.html",
        context={"qs": qs_updated},
    )


# template.html

{% for item in qs %}
    {{ item.accountplan__name }}
    {{ item.amount__sum }}
    {{ item.div_result }}
{% endfor %}
πŸ‘€JPG

Leave a comment