我在文档中找不到任何内容。对于该字段,我们需要提供两个参数:max_digits 和 decimal_places。
class Product(models.Model):
price = models.DecimalField(max_digits=10, decimal_places=2)
以上配置最多存储99999999.99。但是,我想知道这个字段是否有最大或最小限制,类似于其他字段存在这些限制的方式。例如,IntegerField 只能存储从 -2147483648 到 2147483647。
最佳答案
整数字段
对于 IntegerField
,Django 明确提到范围为:
class IntegerField(**options)
An integer. Values from
-2147483648
to2147483647
are safe in all databases supported by Django.
即便如此,这也不是本身的限制,但从那时起,由数据库来支持它。例如 MySQL ,它将采用 INT
,结果范围为 -2'147'483'648 到 2'147'483'647。
十进制字段
如果我们看一下 source code我们看到完成了两项检查:
digits_errors = [ *self._check_decimal_places(), *self._check_max_digits(), ]
如果我们深入研究这些检查,我们只会看到 max_digits
应该大于零(所以 > 0
),decimal_places
code> 大于或等于零(因此 >= 0
)。
但这并不意味着数据库本身会接受它。例如在 MySQL specifications for a DECIMAL
,我们看到:
The declaration syntax for a
DECIMAL
column isDECIMAL(M,D)
. The ranges of values for the arguments are as follows:
M
is the maximum number of digits (the precision). It has a range of 1 to 65.D
is the number of digits to the right of the decimal point (the scale). It has a range of 0 to 30 and must be no larger thanM
.
因此,即使 Django 接受某些值,也不意味着每个后端都会接受这些值。这些也可能因数据库后端而异。例如在 PostgreSQL ,我们有:
up to 131072 digits before the decimal point; up to 16383 digits after the decimal point.
因此最好查阅数据库后端的文档。如果您尝试定义表,您将在迁移中获得错误,因此您可以简单地“尝试”使用如此大的值,并查看数据库是否可以处理它们。
也就是说,65 位数字对于大多数应用程序可能就足够了。最大值大于*Avogadro's constant [wiki]的平方, 所以除非你想对用 Knuth's up-arrow notation [wiki] 更好地表达的数字进行算术运算没有问题。
关于django - 使用 Django 的 DecimalField 可以存储的最大和最小十进制数是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52581017/