‘drop’ Database Command for Django Manager

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
Advertisements
5 comments
  1. rooster said:

    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.

    • 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;

  2. 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.

  3. 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’]])

  4. Tim said:

    Another alternative, although Natim’s is probably the best way (wish I’d read it before I wrote this!)

    from django.conf import settings
    import psycopg2 as db

    def recreateDb():
    print “Connecting…”
    dbinfo = settings.DATABASES[‘default’]
    conn = db.connect(host=dbinfo[‘HOST’], user=dbinfo[‘USER’],
    password=dbinfo[‘PASSWORD’], port=int(dbinfo[‘PORT’] or 5432))
    conn.autocommit = True
    cursor = conn.cursor()
    print “Dropping and creating database %s” % dbinfo[‘NAME’]
    cursor.execute(“DROP DATABASE ” + dbinfo[‘NAME’])
    cursor.execute(“CREATE DATABASE ” + dbinfo[‘NAME’])
    print “Done”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s