Tuesday, December 2, 2008

Using django ORM in a non-django project

One of my latest project is split in 2 interconnected parts, one is using django framework for web interface and the other is third application scecific. And I thought of using django ORM in latter part to keep things simple and not to break anything in database. Quick lookup on internet gave me nothing, so I digged into it and found out that the only thing a script/application needs to use django ORM is DJANGO_SETTINGS_MODULE enviroment variable set. So here comes the solution:

import os

os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
 
from myproject.campaign.models import Campaign, List

The important thing here is not to try to import anything django-specific before actually setting enviroment variable. After that you will be able to use django ORM in your non-django project.

1 comments:

Jeremy said...

I was just trying to decide on an ORM for a new project and I had ruled out Django because I assumed the ORM was glued in.

Thanks for sharing this excellent hack.