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?
If you want to completely wipe the database and resync it in the same go you need something like the following. I also combine adding test data in this command:
#!/usr/bin/env python import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings") # Replace with your app name. from django.db import connection from django.core.management import call_command from django.conf import settings # If you're using postgres you can't use django's sql stuff for some reason that I # can't remember. It has to do with that autocommit thing I think. # import psychodb2 as db def recreateDb(): print("Wiping database") dbinfo = settings.DATABASES['default'] # Postgres version #conn = db.connect(host=dbinfo['HOST'], user=dbinfo['USER'], # password=dbinfo['PASSWORD'], port=int(dbinfo['PORT'] or 5432)) #conn.autocommit = True #cursor = conn.cursor() #cursor.execute("DROP DATABASE " + dbinfo['NAME']) #cursor.execute("CREATE DATABASE " + dbinfo['NAME'] + " WITH ENCODING 'UTF8'") # Default is UTF8, but can be changed so lets be sure. # Mysql version: print("Dropping and creating database " + dbinfo['NAME']) cursor = connection.cursor() cursor.execute("DROP DATABASE " + dbinfo["NAME"] + "; CREATE DATABASE " + dbinfo["NAME"] + "; USE " + dbinfo["NAME"] + ";") print("Done") if __name__ == "__main__": recreateDb(); print("Syncing DB") call_command('syncdb', interactive=False) print("Adding test data") addTestData() # ...
It would be nice to be able to do
cursor.execute(call_command('sqlclear', 'main')) but
call_command prints the SQL to stdout rather than returning it as a string, and I can't work out the