Skip to content

Instantly share code, notes, and snippets.

@nmfzone
Created February 29, 2020 19:33
Show Gist options
  • Save nmfzone/0b6ac9b631a6ad4c1985b9eeb0497564 to your computer and use it in GitHub Desktop.
Save nmfzone/0b6ac9b631a6ad4c1985b9eeb0497564 to your computer and use it in GitHub Desktop.
Django migrate:fresh command
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.db import connection
class Command(BaseCommand):
help = 'Delete all tables and run all migrations'
def add_arguments(self, parser):
parser.add_argument('--seed', nargs='*', help='Run the DB seeders.')
def handle(self, *app_labels, **options):
tables = connection.introspection.table_names()
connection.disable_constraint_checking()
schema_editor = connection.schema_editor()
schema_editor.execute(schema_editor.sql_delete_table % {
'table': ','.join(tables)
})
connection.enable_constraint_checking()
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 Feb 29, 2020

This commands add functionality to Django, when you need to drop all tables, then just migrate all the migrations.
It has an ability to run the database seeder after the migration.

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
---------------- migratefresh.py
---------------- seed.py

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

Tested in Django 2.2

@nmfzone
Copy link
Author

nmfzone commented Oct 27, 2020

If you want another version called migraterefresh (un-apply all migrations), you can go to:

https://gist.github.com/nmfzone/2598d56144f911649385aaaefaac00d7

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