我可以从 Django 中 DecimalField 上的 Avg 返回 Decimal 值吗?

发布于 2024-12-29 23:13:02 字数 403 浏览 4 评论 0原文

当对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

过期情话 2025-01-05 23:13:03

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 (effectively float), text, or blob. Based on this I'd expect the engine to cast any input decimal.Decimal into a real then return it as a float 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 than float, 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文