Skip to content

Instantly share code, notes, and snippets.

@spenthil
Created October 17, 2010 00:49
Show Gist options
  • Save spenthil/630412 to your computer and use it in GitHub Desktop.
Save spenthil/630412 to your computer and use it in GitHub Desktop.
Does the same thing as `django-admin.py inspectdb` but doesn't require you to fully setup a django project first. From django's documentation: 'Introspects the database tables in the database pointed-to by the [database_name] [parameter] and outputs a Dja
#!/usr/bin/env python
__version__ = ['1', '0', '0']
from django.conf import settings
from django.core.management import ManagementUtility
def inspectdb(name, engine='mysql', user='root', password='', host='', port=''):
# setup django
settings.configure(
DATABASES = {
'default': {
'ENGINE': "django.db.backends.%s" % engine,
'NAME': name,
'USER': user,
'PASSWORD': password,
'HOST': host,
'PORT': port,
}
}
)
ManagementUtility().fetch_command('inspectdb').execute()
if __name__ == '__main__':
from optparse import OptionParser
description = "Does the same thing as `django-admin.py inspectdb` but doesn't require you to fully setup a django project first. From django's documentation: 'Introspects the database tables in the database pointed-to by the [database_name] [parameter] and outputs a Django model module (a models.py file) to standard output.'"
usage = "usage: %prog [options] database_name"
parser = OptionParser(usage, version=".".join(__version__), description=description)
parser.add_option('--engine', default='mysql', choices=('postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3', 'oracle'), help="Database engine to use, default is 'mysql'")
parser.add_option('--user', default='root', help="Database user name, default is 'root' - nbot used with sqlite3.")
parser.add_option('--password', default='', help="Database user password, default is '' - not used with sqlite3.")
parser.add_option('--host', default='', help="Database host, default is 'localhost'.")
parser.add_option('--port', default='', help="Database port, default is the default for the database engine - not used with sqlite3.")
(options, args) = parser.parse_args()
name = " ".join(args)
if name == '':
parser.error("Database name required.")
inspectdb(name, **options.__dict__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment