[Django]-Copy a database column into another in Django

33👍

As the comment mentioned, you can simply write a migration for this. I think the below should work though I haven’t tested it. It uses the queryset update API and F to avoid looping

from __future__ import unicode_literals

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


def copy_field(apps, schema):
    MyModel = apps.get_model('<your app>', 'MyModel')
    MyModel.objects.all().update(column_a=F('column_b'))


class Migration(migrations.Migration):
    dependencies = [
        ('<your app>', '<previous migration>'),
    ]

    operations = [
        migrations.RunPython(code=copy_field),
    ]

Leave a comment