'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



Solution 1:[1]

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')))

Solution 2:[2]

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'))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Iain Shelvington
Solution 2