Django基于另一列将十进制数舍入为n位小数

2024-04-24 10:08:36 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我将PostgreSQL和Django用于以下模型

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函数似乎只允许我舍入到整数。根据:https://docs.djangoproject.com/en/3.0/ref/models/database-functions/#round


Tags: todjango模型modelmodelsexamplepostgresqlnum
1条回答
网友
1楼 · 发布于 2024-04-24 10:08:36

内置的Round函数只舍入到最接近的整数。如果您使用的是postgres,您可以添加自己的数据库函数,通过子类化^{}来调用ROUND(),并在查询中使用它

from django.db.models import Func

class RoundWithPlaces(Func):
    function = 'ROUND'

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

相关问题 更多 >