How to move migrations files to outside of django project?

565 views Asked by At
  • django-project/
    • migrations/

      • app1/

      • .../

    • src/

      • app1/

      • .../

      • config/

        • ...

        • settings.py

how to set the path in MIGRATION_MODULES in settings.py to make generated migration files appear in migrations/app1/ folder?

I have tried MIGRATION_MODULES = {'app1': '..migrations.app1.db_migrations'} but got errors.

  1. Is not it a bad practice to move migration files from default location?
2

There are 2 answers

3
Syed Mustafa Nadeem On

To move the migration files outside of your Django project, you can do the following:

  • Make a new directory outside of your Django project to store the migrations files. In your Django project's settings.py file, set the MIGRATION_MODULES setting to a dictionary that maps the app labels to the new directory that you created. For example:
MIGRATION_MODULES = {
    'app_name': 'path.to.migration.module',
}
  • Move the migrations files for each app to the new directory.
  • Run the makemigrations and migrate management commands as usual.
0
Ashley Gasmi On

Here is how to do it.

In settings.py you are going to add these lines:

import os, sys

# Path to django-project/ from __file__ or settings.py
proj_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))

# Path to the migration folder
new_mig_folder = os.path.join(proj_dir, 'migrations/')

# And to add the folder to the path
sys.path.append(new_mig_folder) 
# Hurrah when you execute the code it will know to look for files in this folder

# Tell Django where the migration files are if not default location
MIGRATION_MODULES = {
    'app1': 'app1.folder', # If in subfolder
    'app2': 'app2_mig', # If files directly in migrations/app2_mig/
    'app3': 'whatever_you_want_to_call_it',
    }