INGl0R1AM0R1
INGl0R1AM0R1

Reputation: 1628

Limiting the amount of decimals displayed, django

So i have an issue, which is basically i am displaying a model with decimal fields and i cant limit how many zeros are displayed, basically it looks like there is too many of then, and i was wondering how to limit it?

Here is the template code,

<table class="table table-striped table-dark" width="100%">
    <thead>
        <th>Posicao</th>
        <th>Marca</th>
        <th>Modelo</th>
        <th>Ano</th>
        <th>Média de lucro</th>
    </thead>
    {%for q in query4 %}
    <tr>
        <td>{{forloop.counter}}</td>
        <td>{{q.marca}}</td>
        <td>{{q.modelo}}</td>
        <td>{{q.ano}}</td>
        <td>{{q.medias}} %</td>
    </tr>
    {% endfor%}
</table>

The query backend, query4=DataDB.objects.values('marca','modelo','ano').annotate(medias=Avg('margem_de_lucro')).order_by('-medias')

The modals being called

marca=models.CharField(max_length = 30,error_messages={'required':'Favor inserir uma marca'})
modelo=models.CharField(max_length = 60,error_messages={'required':'Favor inserir um modelo'}) 
ano=models.IntegerField(
    validators=[MinValueValidator(1960,'Favor inserir acima 1960.'), MaxValueValidator(2023,'Favor inserir abaixo 2023.')],
    error_messages={'required':'Favor inserir uma ano'})
margem_de_lucro=models.DecimalField(max_digits= 12,decimal_places=3,max_length= 12)

enter image description here

Upvotes: 1

Views: 1079

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

You can make use of the |floatformat template filter [Django-doc]:

{{ value|floatformat:3 }}

Here the 3 refers to the number of decimal places to use. You can thus set this accordingly.

If you really want to do this in the QuerySet, you can Cast it to a DecimalField with three decimal digits for example:

from django.db.models import Avg, DecimalField
from django.db.models.functions import Cast

query4 = DataDB.objects.values('marca','modelo','ano').annotate(
    medias=Cast(
        Avg('margem_de_lucro'),
        output_field=DecimalField(max_digits=10, decimal_places=3)
    )
).order_by('-medias')

but I would advise against that. Models and views are usually not specifying how something should be rendered, but are focused on storing, receiving and aggregating data.

Upvotes: 2

Related Questions