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.



7 Responses to “Insert Initial Data via Django ORM”  

  1. Works great, nice job.

  2. 2 Anonymous

    Ditto, good solution. Thanks.

  3. 3 Idetrorce

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

  4. Freakin’ sweet! Works like a charm.

  5. 5 Brian Luft

    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!


Leave a Reply