I did this today. I thought I’d write it up so I can remember for next time.

I’m working on another project using Django and have liked using the ORM more than any other of the big Python ORMs out there. On MLKSHK we use the beloved FlyingCow, one that we (Ivan) wrote, but when working for clients I like to use as much existing, tested code out there as possible.

First, create a new directory in the root of your project. Throw two files in there: __init__.py and models.py.

Next, create a settings.py file in your project, fill in the necessary stuff for your database and for INSTALLED_APPS include the name of the directory you made. In this case I made a directory/module called “orm”.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}

INSTALLED_APPS = (
    'orm',
)

Now create your models in models.py. Note the Meta class.

from django.db import models

class Doink(models.Model):
    name = models.CharField(max_length=25, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, null=True)
    class Meta:
        db_table = u'doink'
        app_label= u'orm'

The first attribute:

db_table
is self-explanatory, but
app_label
is there to help Django know this is part of the orm package. Normally it would infer this from the module it lived in inside of Django but since we’re not in Django it breaks without it.

Last thing you need to do is set the DJANGO_SETTINGS_MODULE environment variable:

export DJANGO_SETTINGS_MODULE=settings

You can now run

django-admin.py syncdb  --pythonpath=.
and your models will be created.

In your code, use your models like normal:

from orm.models import Doink
Doink.objects.all()

Doink will now work like any other Django model.