How can I drop all tables from a database using manage.py and command line? Is there any way to do that executing manage.py with appropriate parameters so I can execute it from a .NET application?
相关问题
- Django __str__ returned non-string (type NoneType)
- Django & Amazon SES SMTP. Cannot send email
- Django check user group permissions
- sqlyog export query result as csv
- Django restrict pages to certain users
Here's a south migration version of @peter-g's answer. I often fiddle with raw sql, so this comes in handy as 0001_initial.py for any befuddled apps. It will only work on DBs that support
SHOW TABLES
(like mysql). Substitute something likeSELECT table_name FROM information_schema.tables WHERE table_schema = 'public';
if you use PostgreSQL. Also, I often do this exact same thing for both theforwards
andbackwards
migrations.Coworker/cocoders would kill me if they knew I did this, though.
There's an even simpler answer if you want to delete ALL your tables. You just go to your folder containing the database (which may be called mydatabase.db) and right-click the .db file and push "delete." Old fashioned way, sure-fire to work.
This answer is for postgresql DB:
Run: echo 'drop owned by some_user' | ./manage.py dbshell
NOTE: some_user is the name of the user you use to access the database, see settings.py file:
There's no native Django management command to drop all tables. Both
sqlclear
andreset
require an app name.However, you can install Django Extensions which gives you
manage.py reset_db
, which does exactly what you want (and gives you access to many more useful management commands).If you're using the South package to handle database migrations (highly recommended), then you could just use the
./manage.py migrate appname zero
command.Otherwise, I'd recommend the
./manage.py dbshell
command, piping in SQL commands on standard input.Drops all tables and recreates them:
Explanation:
manage.py sqlclear
- "prints the DROP TABLE SQL statements for the given app name(s)"sed -n "2,$p"
- grabs all lines except first linesed -n "$ !p"
- grabs all lines except last linesed "s/";/" CASCADE;/"
- replaces all semicolons (;) with (CASCADE;)sed -e "1s/^/BEGIN;/" -e "$s/$/COMMIT;/"
- inserts (BEGIN;) as first text, inserts (COMMIT;) as last textmanage.py dbshell
- "Runs the command-line client for the database engine specified in your ENGINE setting, with the connection parameters specified in your USER, PASSWORD, etc., settings"manage.py syncdb
- "Creates the database tables for all apps in INSTALLED_APPS whose tables have not already been created"Dependencies:
Credits:
@Manoj Govindan and @Mike DeSimone for sqlclear piped to dbshell
@jpic for 'sed "s/";/" CASCADE;/"'