Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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?

like image 614
AlGiorgio Avatar asked Dec 06 '22 16:12

AlGiorgio


2 Answers

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.

like image 79
NIKHIL RANE Avatar answered Mar 30 '23 00:03

NIKHIL RANE


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.

like image 33
voodoo-burger Avatar answered Mar 30 '23 00:03

voodoo-burger