The Django manager is a really handy tool. I wrote earlier about making your own custom managers and there is a lot of other great documentation on it.
Django comes with a bunch of helpful management commands like ‘flush’, ‘syncdb’, ‘test’, etc.
I’ve created a generic ‘drop’ command as I felt it was missing. I often found myself going into mysql to drop and re-create a database. This is needed whenever you significantly change your models and need to start over. The ‘drop’ command does that automatically using the database information in your settings file.
The following code is from ‘drop.py’
from django.conf import settingsfrom django.conf import settings
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
help = "Drop and re-create the database"
def handle_noargs(self, **options):
import MySQLdb
print "Connecting..."
db=MySQLdb.connect(host=settings.DATABASE_HOST or "localhost" ,user=settings.DATABASE_USER,
passwd=settings.DATABASE_PASSWORD, port=int(settings.DATABASE_PORT or 3306))
cursor = db.cursor()
print "Dropping database %s" % settings.DATABASE_NAME
cursor.execute("drop database %s; create database %s;" % (settings.DATABASE_NAME, settings.DATABASE_NAME))
print "Dropped"
To install simply place this code in a file called ‘drop.py’ and add it to a management comands folder. If you don’t have a management command folder yet you simply need to create the following file structure in one of your app directories (MY-APP-DIR).
MY-APP-DIR/
management/
__init__.py
commands/
__init__.py
drop.py
Now, whenever you’ need to whipe your database and start fresh you can simply run:
./manage.py drop
Posted by rooster on June 6, 2009 at 1:51 pm
does this work with no initial database created? trying a similar solution with mysql, but without the db there to begin with, get a
File “build/bdist.macosx-10.3-fat/egg/MySQLdb/connections.py”, line 170, in __init__
_mysql_exceptions.OperationalError: (1049, “Unknown database ‘test’”)
obviously, a “drop” would imply the db is there. any hint on how to create it to begin with for the project?
thanks.
Posted by godavemon on June 7, 2009 at 9:15 am
Yep, log into MySQL
mysql -u username -p password
If you haven’t setup a mysql password yet its simply
mysql -u root
to get in. Then to create the database in the mysql shell use
> create database YOUR_DB_NAME;
and if you ever want to drop it manually.
> drop database YOUR_DB_NAME;
Posted by John Mansfield on October 31, 2010 at 11:40 pm
I think there is another (arguably hacky) way to do this:
1. Delete the existing .db file in your Django project;
2. run the “manage.py syncdb” command, so it creates a fresh db.
… Seems to have worked for me.
Posted by Natim (@Natim) on December 13, 2011 at 9:57 am
It did it like this :
from django.db import connection
cursor = connection.cursor()
cursor.execute(“DROP DATABASE %s;”, [connection.settings_dict['NAME']])
cursor.execute(“CREATE DATABASE %s;”, [connection.settings_dict['NAME']])