最佳答案
我计划重命名现有Django项目中的几个模型,其中有许多其他模型与我想要重命名的模型具有外键关系。我相当肯定这将需要多次迁移,但我不确定具体的过程。
假设我从一个名为myapp
的Django应用程序中的以下模型开始:
class Foo(models.Model):
name = models.CharField(unique=True, max_length=32)
description = models.TextField(null=True, blank=True)
class AnotherModel(models.Model):
foo = models.ForeignKey(Foo)
is_awesome = models.BooleanField()
class YetAnotherModel(models.Model):
foo = models.ForeignKey(Foo)
is_ridonkulous = models.BooleanField()
我想将__重命名为ABC0模型,因为该名称实际上没有意义,并且会在代码中引起混淆,而Bar
将使名称更加清晰。
根据我在Django开发文档中读到的内容,我假设迁移策略如下:
修改models.py
:
class Bar(models.Model): # <-- changed model name
name = models.CharField(unique=True, max_length=32)
description = models.TextField(null=True, blank=True)
class AnotherModel(models.Model):
foo = models.ForeignKey(Bar) # <-- changed relation, but not field name
is_awesome = models.BooleanField()
class YetAnotherModel(models.Model):
foo = models.ForeignKey(Bar) # <-- changed relation, but not field name
is_ridonkulous = models.BooleanField()
请注意,foo
的AnotherModel
字段名称不会更改,但关系会更新为Bar
模型。我的理由是,我不应该一次更改太多,如果我将该字段名更改为bar
,则可能会丢失该列中的数据。
创建空迁移:
python manage.py makemigrations --empty myapp
编辑在步骤2中创建的迁移文件中的Migration
类,将RenameModel
操作添加到操作列表中:
class Migration(migrations.Migration):
dependencies = [
('myapp', '0001_initial'),
]
operations = [
migrations.RenameModel('Foo', 'Bar')
]
应用迁移:
python manage.py migrate
在models.py
中编辑相关字段名称:
class Bar(models.Model):
name = models.CharField(unique=True, max_length=32)
description = models.TextField(null=True, blank=True)
class AnotherModel(models.Model):
bar = models.ForeignKey(Bar) # <-- changed field name
is_awesome = models.BooleanField()
class YetAnotherModel(models.Model):
bar = models.ForeignKey(Bar) # <-- changed field name
is_ridonkulous = models.BooleanField()
创建另一个空迁移:
python manage.py makemigrations --empty myapp
编辑在步骤6中创建的迁移文件中的Migration
类,将任何相关字段名的RenameField
操作添加到操作列表中:
class Migration(migrations.Migration):
dependencies = [
('myapp', '0002_rename_fields'), # <-- is this okay?
]
operations = [
migrations.RenameField('AnotherModel', 'foo', 'bar'),
migrations.RenameField('YetAnotherModel', 'foo', 'bar')
]
应用第2次迁移:
python manage.py migrate
除了更新代码的其余部分(视图、表单等)以反映新的变量名之外,这基本上就是新迁移功能的工作方式吗?
而且,这似乎有很多步骤。迁移操作是否可以以某种方式进行压缩?
谢谢!