djangodjango-database

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?


Solution

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