2009-09-15

Using Django's Syncdb outside of Django

I'm working on another project that uses Django's ORM that isn't (yet) a web applicaiton. There's no settings.py file as the application has its own configuration system build on ConfigObj and optparase. But, before you can use the app, you need to create the tables that Django's ORM needs for your Models. If you app lives in a python package named 'fooapp', then put your Django models in fooapp.models and try this code:

from django.conf import settings
from django.core.management.commands import syncdb

opts, args = build_configuration()
my_app = 'fooapp'
settings.configure(
DATABASE_ENGINE=opts['db_engine'],
DATABASE_NAME=opts['db_name'],
DATABASE_USER=opts['db_user'],
DATABASE_PASSWORD=opts['db_pass'],
DATABASE_HOST=opts['db_host'],
DATABASE_PORT=opts['db_port'],
INSTALLED_APPS=(my_app,)
)
cmd = syncdb.Command()
cmd.handle_noargs()



And do let me know if that works. Thanks!

2 comments:

Pythonic Avocado said...

I misspelled optparse.

Anonymous said...

As you're using Blogger, you can just edit your post even after it's published to correct spelling etc.