Last active
September 25, 2023 18:08
-
-
Save adamghill/2f405ac8c70518d095ff3bbcc46a66b6 to your computer and use it in GitHub Desktop.
Start from scratch for database migrations in Django
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
#!/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!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Expanded from https://www.codegrepper.com/code-examples/shell/mac+django+clear+all+migrations.
A few notes:
.venv
, but if you use a different name, tweak line 35 so you don't delete other packages' migration filespostgres
sodropdb
and thencreatedb
are used to re-create the database;mysql
would be different 🤷; forsqlite
just delete the filepoetry
so line 41 and 46 invokemanage.py
throughpoetry
; tweak those lines if you don't usepoetry
Only tested on Mac, YMMV, I take no responsibility if this ruins your hard drive, etc., etc.