【发布时间】:2016-01-03 22:40:52
【问题描述】:
我正在将字段 some_field 从 Model_A 移动到新的 Model_B,并具有 OneToOne 关系。在删除Model_A 中的此字段之前,我想将(历史)Model_A 中的值复制到新创建的Model_B。问题是我无法在迁移时检索该字段,因为Model_A 不再包含some_field。
这是我尝试运行自定义迁移时收到的错误消息:
AttributeError: 'Model_A' object has no attribute 'some_field'
更改前的模型:
class Model_A:
some_field = models.BooleanField(default=False)
some_other_field = models.BooleanField(default=False)
修改后的模型:
class Model_A:
some_other_field = models.BooleanField(default=False)
class Model_B:
model_a = models.OneToOneField(Model_A, related_name='extension')
some_field = models.BooleanField(default=False)
迁移:
class Migration(migrations.Migration):
dependencies = [
('my_app', '0001_initial'),
]
def forwards_func(apps, schema_editor):
# This is where I try to get the "historical" Model_A
Model_A = apps2.get_model("my_app", "Model_A")
# And this is where I intend to copy the some_field values
for model_A_instance in Model_A.objects.all():
b = Model_B(model_a=model_A_instance)
# b gets created correctly, but the following step fails
b.some_field = modelA_instance.some_field
b.save()
operations = [
migrations.CreateModel(
name='Model_B',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('some_field', models.BooleanField(default=False)),
('model_a', models.OneToOneField(related_name='extension', to='my_app.Model_A')),
],
options={
},
bases=(models.Model,),
),
migrations.RunPython(forwards_func),
migrations.RemoveField(
model_name='model_a',
name='some_field',
),
]
我非常清楚我必须以某种方式获取Model_A(=当前数据库中的那个)的“历史”表示,但我认为这就是apps2.get_model("my_app", "Model_A") 部分的用途。
关于如何实现这一点的任何意见?或者我应该将迁移一分为二,第一个创建 Model_B + 复制 some_field 值,第二个从 Model_A 中删除 some_field 字段?
【问题讨论】:
标签: django django-models django-migrations