Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup django migrations to be always the last one applied

I have django application and migration file 002_auto.py, which uses Django RunPython to alter database. I have no idea how much migrations files would be created in future, but I want the file 002_auto.py to be applied as the last part of migration process.

How to set that migrations to be executed as the last one while performing django migrations without need to perform any manual steps each time I want to execute migrate command (or altering dependencies variable each time i've added new migrations)?

p.s. I've looked into django migrations documentation and other articles without success.

like image 378
Andriy Ivaneyko Avatar asked Oct 25 '16 11:10

Andriy Ivaneyko


People also ask

How does Django know which migrations have been applied?

Ensuring that a migration is applied only once requires keeping track of the migrations that have been applied. Django uses a database table called django_migrations . Django automatically creates this table in your database the first time you apply any migrations.

What is difference between migrate and migration in Django?

So the difference between makemigrations and migrate is this: makemigrations auto generates migration files containing changes that need to be applied to the database, but doesn't actually change anyhting in your database. migrate will make the actual modifications to your database, based on the migration files.


1 Answers

You can subclass migrate command and put this code after super call

# project/myapp/management/commands/custom_migrate.py
from django.core.management.commands.migrate import Command as MigrateCommand

class Command(MigrateCommand):
    def handle(self, *args, **options):
        super().handle(*args, **options)
        # put your code from 002_auto.py here

This command should be added to app that is in your INSTALLED_APPS. And then you can call it like this

python manage.py custom_migrate

Read more about custom commands https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/

like image 67
Sardorbek Imomaliev Avatar answered Sep 29 '22 07:09

Sardorbek Imomaliev