1 | initial version |
To transform a string column into an array column in Django PostgreSQL migration, follow these steps:
makemigrations
command:
python manage.py makemigrations your_app_name --empty your_migration_name
PostgreSQL
operation from django.contrib.postgres.operations
.
from django.db import migrations
from django.contrib.postgres.operations import PostgreSQL
Define two operations in the Migration
class: RunSQL
and PostgreSQL
.
class Migration(migrations.Migration):
operations = [
migrations.RunSQL("ALTER TABLE your_table_name ADD COLUMN new_column_name text[];"),
PostgreSQL("UPDATE your_table_name SET new_column_name = ARRAY[column_name];"),
migrations.AlterField(
model_name='your_model_name',
name='new_column_name',
field=ArrayField(models.CharField(max_length=your_max_length)),
),
]
RunSQL
operation, add a SQL statement to create a new array column in the table.
migrations.RunSQL("ALTER TABLE your_table_name ADD COLUMN new_column_name text[];")
PostgreSQL
operation, add a SQL statement to update the values of the new array column from the string column.
PostgreSQL("UPDATE your_table_name SET new_column_name = ARRAY[column_name];")
AlterField
operation, add a new array field to the model, and set the max_length
parameter to the maximum length of the strings in the original column.
migrations.AlterField(
model_name='your_model_name',
name='new_column_name',
field=ArrayField(models.CharField(max_length=your_max_length)),
)
migrate
command:
python manage.py migrate your_app_name
Now, the string column should have been transformed into an array column.