doing the dirty with a db without the sql….

Writing that title almost feels like unprotected sex. It sounds naughty, is a no no but feels very good.

So what am I talking about? Database access in Django, which apparently is an implementation of object relational mapping. What this allows you to do in python is write a class representing a table in your database. Then you can access that table as an instance of that class in your python code. No sql. No mucking with your connection to the database. Now isn’t that sexy?

Well, it’s saving me a hell of a lot of time when prototyping the startup I’m working on. So yesterday I decided that I wanted to use django’s db api in a backend server I’m writing. Since this app would be working inside the same tables as the front end web app I’m building in django, I figured it shouldn’t be too difficult. Did some digging via google and mailing lists but didn’t find the answer I was looking for. So after a bit of hitting the head against the wall, over analyzing of a simple traceback and discussion with some django folks, we came to a very simple solution:

import os, sys
sys.path.append("path/to/project")
os.environ['DJANGO_SETTINGS_MODULE'] = "project.settings"
from project.app import models

You just add your path to your settings.py (for db access variables) and set a variable to the project settings file in the app’s running environment and your done.   Create classes for all of your db tables and you’re good to go with any python app using django for db access. Again, sexy.

For more details hit the docs on the api on django’s site.


About this entry