Jika Anda dalam mode pengembangan dan Anda hanya ingin mengatur ulang semuanya (database, migrasi, dll), saya menggunakan skrip ini berdasarkan jawaban Abdelhamid Ba. Ini akan menghapus tabel database (Postgres), menghapus semua file migrasi, menjalankan kembali migrasi dan memuat perlengkapan awal saya:
#!/usr/bin/env bash
echo "This will wipe out the database, delete migration files, make and apply migrations and load the intial fixtures."
while true; do
read -p "Do you wish to continue?" yn
case $yn in
[Yy]* ) make install; break;;
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
done
echo ">> Deleting old migrations"
find ../../src -path "*/migrations/*.py" -not -name "__init__.py" -delete
# Optional
echo ">> Deleting database"
psql -U db_user -d db_name -a -f ./reset-db.sql
echo ">> Running manage.py makemigrations and migrate"
./migrations.sh
echo ">> Loading initial fixtures"
./load_initial_fixtures.sh
echo ">> Done"
reset-db.sql file:
DO $$ DECLARE
r RECORD;
BEGIN
-- if the schema you operate on is not "current", you will want to
-- replace current_schema() in query with 'schematodeletetablesfrom'
-- *and* update the generate 'DROP...' accordingly.
FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = current_schema()) LOOP
EXECUTE 'DROP TABLE IF EXISTS ' || quote_ident(r.tablename) || ' CASCADE';
END LOOP;
END $$;
file migrasi.sh:
#!/usr/bin/env bash
cd ../../src
./manage.py makemigrations
./manage.py migrate
file load_initial_fixtures.sh:
#!/usr/bin/env bash
cd ../../src
./manage.py loaddata ~/path-to-fixture/fixture.json
Pastikan untuk mengubah jalur yang sesuai dengan aplikasi Anda. Saya pribadi memiliki skrip ini dalam folder bernama project_root / script / local, dan sumber django ada di project_root / src.