Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rounding decimal number to n decimal places based on another column

So I am using PostgreSQL and Django with the following model

class Example(model.Model):
    num = models.DecimalField(max_digits=20, decimal_places=10)
    round_to= models.IntegerField()

What I would like to achieve is that:

Example.objects.annotate(rounded = Round(F('num'),F('round_to'))

But it seems that Round function only allow me to round to integer. According to: https://docs.djangoproject.com/en/3.0/ref/models/database-functions/#round

like image 873
Louis Ng Avatar asked Dec 05 '25 04:12

Louis Ng


2 Answers

This is resolved in Django 4.

The new precision argument of the Round() database function allows specifying the number of decimal places after rounding. Release notes.

from django.db.models.functions import Round

Example.objects.annotate(rounded=Round(F('num'), precision=F('round_to'))
like image 156
ZSmain Avatar answered Dec 06 '25 16:12

ZSmain


The built-in Round function only rounds to the nearest integer. If you are using postgres you can add your own database function to call ROUND() by subclassing Func and use it in your queries

from django.db.models import Func

class RoundWithPlaces(Func):
    function = 'ROUND'

Example.objects.annotate(rounded=RoundWithPlaces(F('num'), F('round_to')))
like image 27
Iain Shelvington Avatar answered Dec 06 '25 17:12

Iain Shelvington