Django ORM Standalone

Sept 03 2012

I find the Django ORM's API to be very well designed. It reduces the amount of work you have to do to load and persist data, and you can also still do the more complex queries. It has sane ways of adding joins and returning already populated related sets in the same query. Add South and you have a great way of managing database migrations.

Sometimes, however, I'm not looking to use all of django. I just need the ORM. It's really simple to do.

First create a still project. We just need a script to run, a module to contain our models, and to set some db settings.

The structure:

app.py
settings.py
manage.py
orm_only/
  __init__.py
  models.py

In settings.py we need to add the normal django db settings:

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
      # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
    'NAME': 'orm_only',                      # Or path to database file if using sqlite3.
    'USER': '',                      # Not used with sqlite3.
    'PASSWORD': '',                  # Not used with sqlite3.
    'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.
    'PORT': '5432',                      # Set to empty string for default. Not used with sqlite3.
  }
}
INSTALLED_APPS     = ("orm_only")

manage.py you can grab from a django app, its the standard version of the file:

#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
  os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
  from django.core.management import execute_from_command_line
  execute_from_command_line(sys.argv)

In models.py we'll define a simple table to get started:

from django.db import models

class NewTable(models.Model):
   text = models.CharField(max_length=255)

Now we can use manage.py to output the sql needed to create our table by running:

./manage.py sql orm_only

That should output our SQL if everything is correctly configured (Note: the database will need to exist)

BEGIN;
CREATE TABLE "orm_only_newtable" (
  "id" serial NOT NULL PRIMARY KEY,
  "text" varchar(255) NOT NULL
)
;
COMMIT;

And that's it. Now to use the django orm in our own script we can import the models and start using them, example from app.py

from django.conf import settings

from django.db import models
from orm_only.models import *

The whole project can be found on github.