Olivia Lundy
Olivia Lundy

Reputation: 127

Decimal numbers in views.py

I am new to Python/Django, so please bear with me! I have simple django views to sum book values:

def portfoyozet(request):
    librarysum = (
        textshare.objects.filter(user_id=request.user.id).aggregate(
            Sum("bookvalue")
        )["bookvalue__sum"]
        or 0
    )
    return render(request, "todo/libsum.html", {"librarysum": librarysum,})

Which is working perfectly but result isn't show decimal values. 4800,30 becomes 4800,00 I dont need to round or something like that here. I just need to show all values with decimal values.It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use. Also found something while googling and change my views.py like:

def portfoyozet(request):
    librarysum = (
        textshare.objects.filter(user_id=request.user.id).aggregate(
            Sum("bookvalue")
        )["bookvalue__sum", 0.00]
        or 0
    )
    return render(request, "todo/libsum.html", {"librarysum": librarysum,})

But it doesnt work either. I have to seek help here as a last resort. I really appreciate if someone could help me out. Thank you in advance.

Upvotes: 1

Views: 234

Answers (1)

Guillaume
Guillaume

Reputation: 2006

What you want to use is output_field argument in Sum, and associate the output of the sum as a FloatField:

from django.db.models import FloatField

#...

librarysum = textshare.objects.filter(user_id=request.user.id).aggregate(Sum('bookvalue', output_field=FloatField()))['bookvalue__sum']

Upvotes: 2

Related Questions