Home > Software engineering >  Django - Divide result of queryset by integer
Django - Divide result of queryset by integer

Time:11-17

I'm fairly new to Django and I'm a bit lost by this. I have this view that shows the sum of a decimal field (amount) grouped by the name of the foreign keys (accountplan):

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,})

I need to divide each annotated amount field in the qs variable by the divider variable. In the template i can loop trough the qs:

{% for item in qs %}
    {{ item.accountplan__name }}
    {{ item.amount__sum }}
{% endfor %}

But when I try do divide the values adding this line in the view:

result = qs / divider

And loop in the template with:

{% for item in result %}
    {{ item.accountplan__name }}
    {{ item.amount__sum }}
{% endfor %}

It shows me an unsupported operand type(s) for /: 'QuerySet' and 'int' error. I understand the error (or at least I think so), and tried to loop in the view like this:

for result in qs:
    result / divider

But I'm still getting the result as a dictionary and the same error as above, except that is 'dict' and 'int'.

Is there a way to do this? Thanks!

CodePudding user response:

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 %}
  • Related