如何将字段从一个模型移到另一个模型,并仍然保留数据? [英] How can I move a field from one model to another, and still retain the data?
问题描述
为简单起见,我有一个模型,例如,
To simplify, I have a model, say,
class Parent(models.Model):
field_a = models.CharField(max_length=40)
以及另一个具有图像字段的模型通过外键到父实例:
and another model that holds an image field, that ties itself to a parent instance via foreign key:
class ParentPicture(models.model):
parent = models.ForeignKey(Parent)
picture = models.ImageField(upload_to=upload_path)
is_used = models.BooleanField(default=False)
最初的计划是为家长提供多张图片,并且一次只能使用一张,但是现在,我希望仅支持一张图片,并包括其中在父模型中,这样就可以销毁 ParentPicture
并使 Parent
看起来像这样:
The original plan was to support multiple pictures for the parent, and only have one in use at any one time, but now, I'd like to have support for just one picture, and include it in the parent model, so that ParentPicture
can be destroyed, and have Parent
look like so:
class Parent(models.Model):
field_a = models.CharField(max_length=40)
picture = models.ImageField(upload_to=upload_path)
我不确定移动图片
字段的最佳方法转到新模型,并包含 ParentPicture
中具有 is_used
标志的实例。
I'm unsure of the best way to move the picture
field over to the new model, and include the instances from the ParentPicture
that have the is_used
flag.
是否有一种简单的方法可以使用Django自动执行此操作,还是我需要对 Parent
模型进行更改,然后迁移更改,然后运行脚本以遍历 ParentPicture
模型并进行适当复制,然后完成 only 操作,然后删除 ParentPicture
模型?
Is there a simple way to do this automatically with Django, or would I need to make the change to the Parent
model, migrate the change, then run a script to go through the ParentPicture
model and copy appropriately, and then only after that's been done, remove the ParentPicture
model?
感谢任何帮助/咨询!
推荐答案
我认为没有一种自动方式移动字段,所以您可以这样做:
I think there is not an 'automatic' way to move the field, so you could do:
- 将
图片
字段添加到Parent
类 - 生成并运行模式迁移
- 编写并运行数据迁移,使用模型
ParentPicture
图片字段> - 删除旧/过时的模型/字段,生成新的架构迁移并运行
- Add
picture
field toParent
class - Generate and run a schema migration
- Write and run a data migration to populate the new
picture
field with values in the modelParentPicture
- Delete old/obsolete models/fields, generate a new schema migration and run it
这篇关于如何将字段从一个模型移到另一个模型,并仍然保留数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!