67

I've discovered that I can set defaults for columns on a postgres database in a django project using migrations.RunSQL('some sql').

I'm currently doing this by adding a column, makemigrations, then removing the column, makemigrations, and then manually modifying the migration file that is produced.

I tried copying an old migration file and then removing the old code so just the new sql could be run and got some strange errors.

CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0067_auto_20180509_2327, 0068_auto_20180514_0707 in csmu).
To fix them run python manage.py makemigrations --merge

How would you create a 'manual' django migration?

Paolo
  • 20,112
  • 21
  • 72
  • 113
Keith John Hutchison
  • 4,955
  • 11
  • 46
  • 64

2 Answers2

135

You can create a manual migration by running the command:

python manage.py makemigrations app_name --name migration_name --empty

Where app_name corresponds to the app within your project you want to add the migration. Remember Django manages both Project and Apps (A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.) And --empty flag is to create a migration file where you will have to add your manual migrations.

For example, on a project where you have an app named api that only has one migration file 0001_initial.py running:

python manage.py makemigrations api --name migration_example --empty

will create a file named 0002_migration_example.py under the directory api/migrations/ that will look like:

# Generated by Django 2.2.10 on 2020-05-26 20:37

from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ('api', '0001_initial'),
    ]

    operations = [
    ]

And you should add migrations.RunSQL('some sql'). inside operations brackets, like:

    operations = [
      migrations.RunSQL('some sql')
    ]
chris Frisina
  • 19,086
  • 22
  • 87
  • 167
Cesar Augusto Garcia
  • 1,476
  • 1
  • 6
  • 4
11

You can learn how to make migrations by investigating the automatically generated migrations, for example:


class Migration(migrations.Migration):

    dependencies = [
        ('app_details', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            ...,
        ),
        migrations.CreateModel(
            ...,
        ),
        migrations.RenameModel(
            ...,
        ),
        migrations.RenameField(
            ...,
        ),
        migrations.RemoveModel(
            ...,
        ),
        # and so on
    ]


Create a manual migration file

use this command in the terminal: python manage.py makemigrations --empty. Then add what you want in it.

notice: you have to compose between the "models.py" and the manual migrations.

Mohammed Samir
  • 376
  • 3
  • 9