在我的模型中,我有旧领域
tag
并创建了新领域tags
。
tag = models.CharField(max_length=64, null=True, default=None, db_index=True, choices=[(tag, tag) for tag in TAGS])
tags = ArrayField(models.CharField(max_length=64, choices=[(tag, tag) for tag in TAGS]), db_index=True, null=True)
。
tag
列只有字符串,例如“APPLE”或“PEAR”。
我希望该列 tags
是迁移后一个字符串的数组。
在创建新字段之后和删除旧字段之前的迁移中,我想将数据从列
tag
传输到tags
。我尝试使用原始 sql:cursor.execute("UPDATE form_builder_formfield SET tags = ARRAY[tag] WHERE tag IS NOT NULL")
但这不起作用。
我收到错误:
django.db.utils.DataError: malformed array literal: "["APPLE"]"
"[" must introduce explicitly-specified array dimensions.
我也尝试过使用 django 查询集,但我总是以上面的错误结束。有什么想法吗?
您可以将 RunPython 操作添加到迁移中。进行迁移,有 2 个操作:添加一个新字段
tags
并删除旧的 tag
。在它们之间添加一个操作波纹管:
migrations.RunPython(migrate_tag_data, reverse_code=reverse_tags),
您可以随意制作
migrate_tag_data
,但我建议使用以下代码。把它放在迁移文件的开头。
def migrate_tag_data(apps, schema_editor):
YOUR_MODEL = apps.get_model("YOUR_APP", "YOUR_MODEL")
for instance in YOUR_MODEL.objects.all():
instance.tags = [instance.tag]
instance.save()
def reverse_tags(apps, schema_editor):
YOUR_MODEL = apps.get_model("YOUR_APP", "YOUR_MODEL")
for instance in YOUR_MODEL.objects.all():
instance.tag = next(instance.tags, None)
instance.save()
然后迁移就可以了!