mimo
mimo

Reputation: 2629

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?

Upvotes: 22

Views: 11522

Answers (2)

Baraa Al-jabali
Baraa Al-jabali

Reputation: 147

You can use raw sql queries in the migration file; achieving the goal & to avoid performance issues related to the ORM.

from django.db import migrations, models


def copy_field(apps, schema_editor):
     with schema_editor.connection.cursor() as cursor:
     cursor.execute("UPDATE <your_model_table_nae> SET column_a = column_b;")


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

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

Upvotes: 0

Rafi Goldfarb
Rafi Goldfarb

Reputation: 601

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),
    ]

Upvotes: 35

Related Questions