Django 根据另一列将小数四舍五入到 n 位小数

Lou*_* Ng 2 python django django-models

所以我使用 PostgreSQL 和 Django 以及以下模型

class Example(model.Model):
    num = models.DecimalField(max_digits=20, decimal_places=10)
    round_to= models.IntegerField()
Run Code Online (Sandbox Code Playgroud)

我想要实现的是:

Example.objects.annotate(rounded = Round(F('num'),F('round_to'))
Run Code Online (Sandbox Code Playgroud)

但似乎该Round函数只允许我四舍五入为整数。根据:https://docs.djangoproject.com/en/3.0/ref/models/database-functions/#round

ZSm*_*ain 7

这个问题在 Django 4 中已得到解决。

数据库函数的新精度参数Round()允许指定四舍五入后的小数位数。发行说明

from django.db.models.functions import Round

Example.objects.annotate(rounded=Round(F('num'), precision=F('round_to'))
Run Code Online (Sandbox Code Playgroud)