Created
February 29, 2020 19:33
-
-
Save nmfzone/0b6ac9b631a6ad4c1985b9eeb0497564 to your computer and use it in GitHub Desktop.
Django migrate:fresh command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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']) |
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
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 seederpython manage.py migratefresh --seed
Tested in Django 2.2