[Fixed]-How can I move a field from one model to another, and still retain the data?

17👍

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

5👍

This is a multistep process. First you need to add the fields to as follows and then do ./manage.py makemigrations

class Parent(models.Model):
    field_a = models.CharField(max_length=40)    
    picture = models.ImageField(upload_to=upload_path)
    is_used = models.BooleanField(default=False)

For the second step you have two options. The first is to create a migrations.RunPython that queries the ParentPicture table and updates the Parent table with the values from it. This wouldn’t involve in raw sql but it would be inefficient. On the other hand if you have only a few rows it wouldn’t matter.

  for p in ParentPicture.objects.all():
      Parent.objects.filter(pk = p.parent_id
           ).update(picture=p.picture, is_used=p.is_used)

The alternative is to use a migrations.RunSQL with an UPDATE JOIN type of query. This will be efficient and recommended if you have a large number of records. In mysql your query might look like this:

UPDATE app_parent p 
   INNER JOIN app_parentpicture pp on
      p.id = pp.parent_id
   SET p.picture = pp.picture, 
      p.is_used = pp.is_used

Step 3, do you really need to drop the old table at this stage? Why not wait until some thorough testing has been done?

👤e4c5

Leave a comment