Skip to content

Instantly share code, notes, and snippets.

@nmfzone
Last active February 29, 2020 19:32
Show Gist options
  • Save nmfzone/2598d56144f911649385aaaefaac00d7 to your computer and use it in GitHub Desktop.
Save nmfzone/2598d56144f911649385aaaefaac00d7 to your computer and use it in GitHub Desktop.
Django migrate:refresh command
from django.apps import apps
from django.apps.config import AppConfig
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Reset and re-run all migrations'
def add_arguments(self, parser):
parser.add_argument('--seed', nargs='*', help='Run the DB seeders.')
def handle(self, *app_labels, **options):
try:
if app_labels and len(app_labels) > 0:
app_configs = [apps.get_app_config(app_label) for app_label in app_labels]
else:
app_configs = [AppConfig.create(app_label) for app_label in settings.INSTALLED_APPS]
except (LookupError, ImportError) as e:
raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
for app_config in app_configs:
try:
call_command('migrate', app_config.name.split('.')[-1], 'zero')
except CommandError:
continue
call_command('migrate')
if options['seed'] is not None:
if len(options['seed']) == 0:
call_command('seed')
else:
call_command('seed', *options['seed'])
@nmfzone
Copy link
Author

nmfzone commented Dec 20, 2019

This commands add functionality to Django, when you need to un-apply migrations from all apps, then just re-apply.
It has an ability to run the database seeder after re-apply the migrations.

You can follow this tutorial to add database seeder functionality to your Django.

You just need to place that code something like this.

---- app
-------- __init__.py
-------- management
------------ __init__.py
------------ commands
---------------- __init__.py
---------------- migraterefresh.py
---------------- seed.py

Then, you can run it using command python manage.py migraterefresh or with seeder python manage.py migraterefresh --seed

Tested in Django 2.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment