如何将字段从一个模型移到另一个模型,并仍然保留数据? [英] How can I move a field from one model to another, and still retain the data?

查看:99
本文介绍了如何将字段从一个模型移到另一个模型,并仍然保留数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为简单起见,我有一个模型,例如,

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:


  1. 图片字段添加到 Parent

  2. 生成并运行模式迁移

  3. 编写并运行数据迁移,使用模型 ParentPicture 图片字段>
  4. 删除旧/过时的模型/字段,生成新的架构迁移并运行

  1. Add picture field to Parent class
  2. Generate and run a schema migration
  3. Write and run a data migration to populate the new picture field with values in the model ParentPicture
  4. Delete old/obsolete models/fields, generate a new schema migration and run it

这篇关于如何将字段从一个模型移到另一个模型,并仍然保留数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆