1

I have a queryset

queryset = BigTable.objects.values('field1__code', 'field2__code').annotate(Sum('field3'))
  • the resulting value field3__sum = "1234567" is an integer and is very long for my template.
  • How can I divide it by 1000 (for example) and get out it a decimal like "1234,5" ?
  • Thank you
cegthgtlhj
  • 191
  • 1
  • 8

1 Answers1

0

You can divide the sum by 1'000 by wrapping this in a Value(..):

from django.db.models import FloatField, Sum, Value

queryset = BigTable.objects.values(
    'field1__code', 'field2__code'
).annotate(
    field3_sum=Sum('field3', output_field=FloatField())/Value(1000, output_field=FloatField())
)

It might however be better to name your field not field3_sum, since that gives a wrong impression. Perhaps you can use field3_sumdiv1000 for example.

In your template you can render with the |floatformat template filter [Django-doc], for example:

{{ object.field3_sum|floatformat }}
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555