Issue
I have two simple migrations:
0001_initial.py
# Generated by Django 4.2.7 on 2023-11-30 11:15
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.RunSQL(
"""
CREATE TABLE comments (
id SERIAL PRIMARY KEY,
contents VARCHAR(240) NOT NULL
);
"""
),
]
0002.py
# Generated by Django 4.2.7 on 2023-11-30 11:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("polls", "0001_initial")
]
operations = [
migrations.RunSQL(
"""
ALTER TABLE comments RENAME COLUMN contents to text;
"""
),
]
I run:
python manage.py migrate
Then I want to undo the 0002 migration
I run
python manage.py migrate polls 0001
But Django does not know how to undo the changes from the second migration.
How can I tell Django that for undoing the changes from the 0002 migration I need to run this SQL:
ALTER TABLE comments RENAME COLUMN text to contents;
I tried searching but without success.
Solution
The RunSQL
migration [Django-doc] takes a second optional parameter where you can specify the reverse migration, so:
class Migration(migrations.Migration):
dependencies = [('polls', '0001_initial')]
operations = [
migrations.RunSQL(
'ALTER TABLE comments RENAME COLUMN contents TO text;',
'ALTER TABLE comments RENAME COLUMN text TO contents;',
),
]
If you then migrate to:
manage.py migrate polls 0001
it will look if all migrations have a reverse operation, and take that query.
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.