如果在 Django 模型中更改 Decimals decimal_places,现有数据会发生什么情况?

What happens with the existing data if Decimals decimal_places are changed in a Django model?

我需要将 DecimalFielddecimal_places=0 更改为 decimal_places=7,同时保持 max_digits=50。我认为此列中的所有数字都在 0 到 1,000,000,000 之间。因此数据迁移可能没有问题。但是,我不确定。

我看过AlterField documentation and I think I found the source code。但是,我需要对此进行介绍。是否可以查看生成的 SQL 查询?

我可以想象出一些错误:

最后两种情况在我的具体情况下不应该发生,但我仍然对 Django 迁移如何处理越界情况感兴趣。

Is it possible to see the generated SQL queries?

是的,可以看到生成的 SQL 查询。您可以使用 sqlmigrate [Django docs] 管理命令(app_label 是您的应用名称,migration_name 是迁移名称,例如 00010002, 等等):

python manage.py sqlmigrate <app_label> <migration_name>

这为我输出了以下 SQL:

BEGIN;
--
-- Alter field field_name on model_name
--
ALTER TABLE "table_name" ALTER COLUMN "field_name" TYPE numeric(50, 7);
COMMIT;

根据 Numeric Types: 8.1.2. Arbitrary Precision Numbers 上的 PostgeSQL 文档,关于您的问题是否会出错:

if the number of digits to the left of the decimal point exceeds the declared precision minus the declared scale, an error is raised.

同样来自 PostgreSQL 文档 Modifying Tables: 5.5.6. Changing a Column's Data Type:

This will succeed only if each existing entry in the column can be converted to the new type by an implicit cast. If a more complex conversion is needed, you can add a USING clause that specifies how to compute the new values from the old.

因此,如果无法进行迁移,则会导致错误。