Custom file names for migration in Django

The process of implementing changes to the database schema is known as migration. For each model, Django creates a migration file in the migration folder. These are called auto migrations. We can also write our own migrations without auto-generating it.

Manual migrations in Django

The following command can be used to create manual migration in Django:

python makemigrations --empty --name filename app_name 

empty flag is indicated to create an empty migration file in which you can add your manual migration. app_name indicates the name of the app in which you want to create the migration file.

The above command will create a migration with name .  But, it adds the prefix 0001 to the filename. If multiple developers are working in different branches of the project, they might get a conflict as migration files might have the same names from different branches.

Custom filename to migration

We can create our own Django management commands for our apps. Create a management/commands directory inside an app directory. Then, create a file and add a Command class that inherits and override the write_migration_files method. Below is given example of the same:


from import Command as MakeMigrationsCommand

class Command(MakeMigrationsCommand):
   def write_migration_files(self, changes):
       for value in changes.values():
          value[0].name = value[0].name.split('_')[1]
       super(Command, self).write_migration_files(changes)

Now, if we run the same command again, a migration file with the name is created. You can add your own logic for filename as well.

Best practice for naming file is timestamp_filename as it sorts the migration files and also avoids the name conflicts.

Ajinkya Chikhale

Ajinkya Chikhale

Software Engineer