Django migrations

Django migrations

Django migrations — Are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema.

Django migrations — Entirely derived from your models file, and are essentially a history that Django can roll through to update your database schema to match your current models.

from django.db import migrations, models

class Migration(migrations.Migration):

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

    operations = [
        migrations.DeleteModel('Tribble'),
        migrations.AddField('Author', 'rating', models.IntegerField(default=0)),
    ]
  • Migrations’re designed to be mostly automatic, but you’ll need to know when to make migrations, when to run them, and the common problems you might run into.
  • Version control system for your database schema.
  • Will run the same way on the same dataset and produce consistent results, meaning that what you see in development and staging is, under the same circumstances, exactly what will happen in production.
  • Django will make migrations for any change to your models or fields - even options that don’t affect the database - as the only way it can reconstruct a field correctly is to have all the changes in the history, and you might need those options in some data migrations later on (for example, if you’ve set custom validators).
  • The migration files for each app live in a “migrations” directory inside of that app, and are designed to be committed to, and distributed as part of, its codebase.
  • The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file and the database migrations shipped with the app.

Squashing migrations

Squashing migrations — Is the act of reducing an existing set of many migrations down to one (or sometimes a few) migrations which still represent the same changes.

$ ./manage.py squashmigrations myapp 0004

Creating migration

$ python manage.py makemigrations your_app_label

Django migrations — Structure map

Clickable & Draggable!

Django migrations — Related pages: