[英]Django rounding decimal number to n decimal places based on another column
所以我将 PostgreSQL 和 Django 与以下 model 一起使用
class Example(model.Model):
num = models.DecimalField(max_digits=20, decimal_places=10)
round_to= models.IntegerField()
我想要实现的是:
Example.objects.annotate(rounded = Round(F('num'),F('round_to'))
但似乎Round
function 只允许我四舍五入到 integer。根据: https://docs.djangoproject.com/en/3.0/ref/models/database-functions/#round
这在Django 4中得到解决。
Round()
数据库 function 的新精度参数允许指定舍入后的小数位数。 发行说明。
from django.db.models.functions import Round
Example.objects.annotate(rounded=Round(F('num'), precision=F('round_to'))
内置Round
function 仅四舍五入到最接近的 integer。 如果您使用的是 postgres,您可以添加自己的数据库 function 通过子类化Func
来调用ROUND()
并在查询中使用它
from django.db.models import Func
class RoundWithPlaces(Func):
function = 'ROUND'
Example.objects.annotate(rounded=RoundWithPlaces(F('num'), F('round_to')))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.