AlGiorgio
AlGiorgio

Reputation: 497

Copy values from existing field when create new field of the same model

I have django 1.10 project. There are I have a model Feedback:

class Feedback(FirstMixin, SecondMixin, models.Model):
    company = models.OneToOneField(
        verbose_name='Company',
        to=Company,
        related_name='feedback'
    )

This model exists and DB table's column Company is filled by keys to Company's items.

Now I need to add some new field to the model:

custom_name = models.CharField(
    verbose_name='Company Custom Name',
    null=False,
    max_length=settings.DATABASE_STRING_LENGTH
)

This field should store custom names of Companies.

What should I do to make values of this field the same as relevant Companies names during migration? Should I change migration's code or is there are some way to define it in model?

Upvotes: 5

Views: 6658

Answers (2)

NIKHIL RANE
NIKHIL RANE

Reputation: 4092

Yes you want to change a migration file that are created. Try to use following solution

from django.db import migrations, models
from django.db.models import F

def migrate_custome_name(apps, schema_editor):
    Feedback = apps.get_model("app_name","Feedback")
    Feedback.objects.all().update(
        custom_name=F('company'))

class Migration(migrations.Migration):

    dependencies = [
        ------
    ]

    operations = [
        migrations.AddField(
            model_name='feedback',
            name='custom_name',
            -- your code --
        ),
        migrations.RunPython(migrate_custome_name), # Add this function to migrate data
    ]

Hope this will help you.

Upvotes: 15

voodoo-burger
voodoo-burger

Reputation: 2153

You can use a data migration, see the Django docs here: https://docs.djangoproject.com/en/1.10/topics/migrations/#data-migrations . You will need to run the operation that sets Feedback.custom_name = Feedback.company after applying the changes to the table.

Upvotes: 1

Related Questions