Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

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)

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.

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?

Thanks for any help/advice!

like image 959
echolocation Avatar asked May 11 '16 18:05

echolocation


1 Answers

I think there is not an 'automatic' way to move the field, so you could do:

  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
like image 144
trinchet Avatar answered Oct 05 '22 16:10

trinchet