I'm working with Django and I'm taking an average for some column values, however the result is rounded up and I'd like to make it one or two decimal places. My goal is to see the result look like 3.5
instead of 4
.
My model is named Application
and the columns have an IntegerField model type. My database is PostgreSQL.
Here's the query that I'm using to currently take the average of my column values:
ratings = Application.objects.filter(id = review.id).annotate(rate = (F('col_1')+F('col_2')+F('col_3')+F('col_4')+F('col_5')+F('col_6'))/6)
I've already tried playing with FloatField
s, but maybe I did it wrong.
Any suggestions?
Thanks in advance!
EDIT: Here is my model for the columns.
col_1 = models.IntegerField(choices=USER_CHOICE)
...
col_6 = models.IntegerField(choices=USER_CHOICE)
You can use an ExpressionWrapper
[Django-doc] here to set this to a FloatField
[Django-doc] or DecimalField
:
from django.db.models import ExpressionWrapper, FloatField
ratings = Application.objects.filter(id=review.id).annotate(
rate=ExpressionWrapper(
(F('col_1')+F('col_2')+F('col_3')+F('col_4')+F('col_5')+F('col_6'))/6,
output_field=FloatField()
)
)
Depending on the situation, it might be better to use a FloatField
or a DecimalField
[Django-doc].