Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a database column into another in Django

I am writing a migration that requires me to fill a field with existing data from another field (with same type and constraints). Is it possible in Django to copy the data in a single operation? The destination column already exists when I need to copy the data.

In SQL, I would have written something like that:

UPDATE my_table SET column_b = column_a;

Edit

The current answer proposes to loop over the model instances, but that is what I want to avoid. Can it be done without a loop?

like image 463
mimo Avatar asked Jan 06 '17 07:01

mimo


1 Answers

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(app, 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(copy_field),
    ]
like image 164
Rafi Goldfarb Avatar answered Oct 01 '22 15:10

Rafi Goldfarb