在 Django 迁移中更改外键名称

时间:2021-01-22 13:40:42

标签: django postgresql migration database-migration

我希望将外键的名称从 uuid 更改为 uuid_erp

为此,我可以按如下方式运行迁移:

migrations.RunSQL('''
    ALTER TABLE result_suppliers 
    RENAME COLUMN uuid TO uuid_erp;
''')

通过这样做,我本质上是想为 django 进行迁移,并且在运行 makemigrations 时它什么也不做。

但是,当我运行 python manage.py makemigrations 时,我看到 django 正在尝试创建列 uuid_erp(已创建)。这给出了信息:

You are trying to add a non-nullable field 'uuid_erp' to resultsuppliers without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option: 

makemigrations docs 我看到那个 django:

<块引用>

根据检测到的模型更改创建新的迁移。

这并不能深入了解如何检测更改。

我的问题有两个:

  • makemigrations 如何确定要进行迁移? (我可以让它跳过某个操作)
  • 如何执行此操作?

注意。如果我使用 makemigrations 而不是自定义重命名命令,django 会删除并重新创建 uuid_erp,并且 uuid 中的现有信息将丢失。

1 个答案:

答案 0 :(得分:0)

这听起来像是 SeparateDatabaseAndState 的一个很好的用例。有一个很好的例子来说明如何做到这一点here