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
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'))
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')))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With