在生产中添加整数primary_key

问题描述 投票:0回答:1

我们有一个正在运行的 Django 后端实例。在一些模型上,我们使用 CharField 作为主键,因为它是满足旧需求的最佳解决方案。现在我们需要添加一个基本的 int id,例如

id = models.AutoField(primary_key=True)

并让旧的炭场保持原状

primary_key=False

我从旧的主键属性中删除了

primary_key=True
标志并触发了
./manage.py makemigrations
。如果我没有声明任何主键,Django 就会像上面提到的那样生成其正常的 id。但触发后,Djang 会要求该模型的旧条目提供默认值,例如:

It is impossible to add a non-nullable field 'id' to anrede without specifying a default. This is because 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 manually define a default value in models.py.

因为它是一个独特的字段,所以我不能使用任何静态内容。那么如何在不删除旧迁移的情况下仍然进行迁移呢?

django primary-key django-migrations
1个回答
0
投票

实现这一点的通常方法是:

  1. 向模型添加一个新的(非唯一、可为空)
    id
    字段并生成迁移脚本。
  2. 编写一个数据迁移,以增量方式填充现有记录的
    id
    列。
  3. primary_key=True
    添加到新的
    id
    字段(并删除
    null=True
    )并生成迁移脚本。

现在您将拥有 3 个迁移,当按该顺序执行时,它们应该可以完成您想要的操作。

请注意,您还应该使用

sqlsequencereset
管理命令重置自动增量计数器。您还应该考虑引用此模型的外键(如果有)。

© www.soinside.com 2019 - 2024. All rights reserved.