Skip to content

Instantly share code, notes, and snippets.

@yardensachs
Last active August 12, 2024 01:19
Show Gist options
  • Save yardensachs/31759edb1c6315172bec150f76c7805a to your computer and use it in GitHub Desktop.
Save yardensachs/31759edb1c6315172bec150f76c7805a to your computer and use it in GitHub Desktop.
This Django management command deletes all migration records from the django_migrations table, and recreates a fake initial migration record. This can be helpful for resetting the migration history during development.
"""
This Django management command deletes all migration records from the django_migrations table,
and recreates a fake initial migration record.
Usage:
python manage.py resetmigrations --database=<database_name>
"""
from django.core import management
from django.core.management.base import BaseCommand, CommandParser
from django.db import DEFAULT_DB_ALIAS, connections, transaction
from django.db.migrations.recorder import MigrationRecorder
class Command(BaseCommand):
help = "Deletes all migration records from the django_migrations table, and recreates a fake initial migration record."
output_transaction = True
def add_arguments(self, parser: CommandParser) -> None:
super().add_arguments(parser)
parser.add_argument(
"--database",
default=DEFAULT_DB_ALIAS,
)
def handle(self, *args, **options) -> None:
self.selected_database = options["database"]
self.verbosity = options["verbosity"]
if self.verbosity > 0:
self.stdout.write("Resetting migrations...")
try:
with transaction.atomic(using=self.selected_database):
self._print_migration_status("Print current migration status")
if self.verbosity > 0:
self.stdout.write("Flushes all migrations...")
MigrationRecorder(
connection=connections[self.selected_database],
).flush()
self._print_migration_status("Print current migration status - should be empty")
if self.verbosity > 0:
self.stdout.write("Recreate fake initial migration")
management.call_command("migrate", fake=True, verbosity=self.verbosity, database=self.selected_database)
self._print_migration_status("Print current migration status - should have the fake initial migration")
if self.verbosity > 0:
self.stdout.write(self.style.SUCCESS("Done!"))
except Exception as e:
if self.verbosity > 0:
self.stdout.write(self.style.ERROR(f"An error occurred: {e}"))
def _print_migration_status(self, message: str) -> None:
if self.verbosity > 1:
self.stdout.write(message)
management.call_command("showmigrations", database=self.selected_database)
@yardensachs
Copy link
Author

@lena fyi

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