我可以从 Django 中 DecimalField 上的 Avg 返回 Decimal 值吗?
当对 models.DecimalField
使用 Avg
聚合时,返回的值是 float
,而不是 decimal.Decimal
代码>.这是因为我的特定数据库(在本例中为 sqlite3)不支持小数形式的聚合值吗?如果是的话,有数据库可以做到吗?有没有办法解决这个问题(即,一种以小数形式返回值的方法),以便可以进行精确的十进制数学计算(而且,无需将 float
转换为 str< /code> 然后返回
decimal.Decimal
)?
注意:我并不是在与那些认为“足够准确”与“准确”相同的人进行争论,也不是为了讨论因错误的基于浮点数的算术而导致星舰企业号坠毁的讨论。
When using the Avg
aggregate for a models.DecimalField
, the returned value is a float
, instead of a decimal.Decimal
. Is this because my specific database (in this case sqlite3) doesn't support aggregate values as decimals? If so, are there databases that do? Is there a way around this (ie, a way to get the value back as a decimal), so that accurate decimal math can be done (also, without converting the float
to a str
and then back to a decimal.Decimal
)?
Note: I'm not trolling for fights with people who believe that "accurate enough" is the same as "accurate", or flame baiting for discussions about the Star Ship Enterprise crashing due to erroneous, float-based arithmetic.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从 SQLLite 3 手册中,支持的数据类型为
null
、整数
、实数
(实际上是浮点
)、文本
或blob
。基于此,我希望引擎将任何输入decimal.Decimal
转换为real
,然后将其作为float
返回给您,因为它不想将其提升到超过其准确性。大多数实际数据库(除了原型之外,我几乎不会考虑使用 sqllite)支持十进制数据类型。我知道 MySQL 会。至于它们是否返回
decimal.Decimal
而不是float
,不幸的是我无法告诉你,因为我还没有调查它们的准确性,float
对我来说已经足够好了。不过,这将是一个很好的起点。From the SQLLite 3 manual, supported data types are
null
,integer
,real
(effectivelyfloat
),text
, orblob
. Based on this I'd expect the engine to cast any inputdecimal.Decimal
into areal
then return it as afloat
to you, since it wouldn't want to upcast it past it's accuracy.Most actual databases (I'd hardly consider sqllite for anything more than a prototype) support decimal data types. I know MySQL does. As to whether or not they return
decimal.Decimal
rather thanfloat
, I couldn't tell you unfortunately as I haven't done the investigation into their accuracy,float
has been good enough for me. It'd be a good place to start though.