Skip to content

Instantly share code, notes, and snippets.

@adamghill
Last active September 25, 2023 18:08
Show Gist options
  • Save adamghill/2f405ac8c70518d095ff3bbcc46a66b6 to your computer and use it in GitHub Desktop.
Save adamghill/2f405ac8c70518d095ff3bbcc46a66b6 to your computer and use it in GitHub Desktop.
Start from scratch for database migrations in Django
#!/bin/sh
set -e
die () {
echo >&2 "$@"
exit 1
}
[ "$#" -eq 1 ] || die "Database name argument is required"
read -p "Re-create the '$1' database? " -n 1 -r
echo
echo "Dropping '$1'..."
dropdb --if-exists $1
echo "'$1' dropped!"
echo
echo "Creating '$1'..."
createdb $1
echo "'$1' created!"
migration_files=`find . -path "*/migrations/*.py" -type f -not -name "__init__.py" -not -path "./.venv/*"`
echo
echo "All migration files:"
echo "$migration_files"
echo
read -p "Delete migration files listed above? " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
echo "Deleting all migration files..."
find . -path "*/migrations/*.py" -type f -not -name "__init__.py" -not -path "./.venv/*" -delete
find . -path "*/migrations/*.pyc" -type f -not -name "__init__.py" -not -path "./.venv/*" -delete
echo "All migration files deleted!"
fi
echo
echo "Creating new migration files..."
poetry run python manage.py makemigrations
echo "New migration files created!"
echo
echo "Migrating the database..."
poetry run python manage.py migrate
echo "Database has been migrated!"
@adamghill
Copy link
Author

adamghill commented Nov 6, 2021

Expanded from https://www.codegrepper.com/code-examples/shell/mac+django+clear+all+migrations.

A few notes:

  • I always have my virtual environment stored at .venv, but if you use a different name, tweak line 35 so you don't delete other packages' migration files
  • I use postgres so dropdb and then createdb are used to re-create the database; mysql would be different 🤷; for sqlite just delete the file
  • I use poetry so line 41 and 46 invoke manage.py through poetry; tweak those lines if you don't use poetry

Only tested on Mac, YMMV, I take no responsibility if this ruins your hard drive, etc., etc.

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