Skip to content

Insert Initial Data via Django ORM

February 18, 2007

In Django we can insert initial data to the database using raw SQL. While it is a nice feature it would be a fantastic if we could use Django’s ORM since it would be compatible with whatever database back-end we use. There is a guide in the Django Wiki for that but it would be perfect if we can integrate the data insertion with syncdb. By using Django’s signals/dispatcher functionality, we can!

First of all create in your Django application directory a file called management.py. Add this code to that file:

from django.dispatch import dispatcher
from django.db.models import signals

import models

def post_syncdb(signal, sender, app, created_models):
    # only run when our model got created
    if (signal == signals.post_syncdb) and (app == models):
        models.install()

dispatcher.connect(post_syncdb, signal=signals.post_syncdb)

And then add this code to your models.py:

def install():
    # change Blog here with your model name
    if Blog.objects.count() > 0:
        return    

    # Create objects here using Django ORM
    Blog(title="My Blog", tagline="Hello World").save()

You can type in your data insertion using Django’s ORM inside the install() function within models.py. The data will be inserted everytime you run syncdb.

Advertisement
10 Comments
  1. Works great, nice job.

  2. Anonymous permalink

    Ditto, good solution. Thanks.

  3. Idetrorce permalink

    very interesting, but I don’t agree with you
    Idetrorce

  4. Freakin’ sweet! Works like a charm.

  5. Brian Luft permalink

    The trunk has had the ability to use fixtures for a while now, which will provide similar functionality.

  6. @Brian: when you’re in a very early stage, generating an XML or JSON files might be tedious. Plus you would need to run two commands instead of one :)

    Each method has their own plus and minuses.

  7. This was immensely useful in figuring out how to hook up inserting PostGIS SQL for unit tests in a GeoDjango app. Thanks!

  8. Thanks for this post. I am new at python and this was a big help.

  9. Stephen White permalink

    Even with fixtures the approach described here has the advantage of making it easy to base the initial data on the contents of django.conf.settings or similar.

    There are some slight changes needed for this to work with current versions: **kwargs needs adding to the declaration of post_syncdb and the connect line should read:

    signals.post_syncdb.connect(post_syncdb)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: