Initialising application data in Django

9 PM July 12, 2006

I found an alternate way to initialise Django application data. The usual method is to create specially named SQL data files (as described in the documentation) which are executed as syncdb creates your model tables. SQL is generally adequate, but sometimes, more complex initialisation is best be in code.

To run your own code each time syncdb is executed, Put the following code into a file named, in your application directory (the same directory as

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

def init_data():
    # Your initialisation code here

dispatcher.connect(init_data, sender=models, signal=signals.post_syncdb)

Here’s how it works. When you run syncdb, Django first imports each application’s The last line of code in this module (dispatch.connect…), tells the Django dispatcher to listen out for the ”post_syncdb” signal, and to call the init_data function when it hears it. Later, when syncdb completes, it fires the post_syncdb signal, which cases the dispatcher to call your init_data function.

The net effect is, each time you do a syncdb, @init_data is called.

By alang | # | Comments (4)
(Posted to Software Development and Python)
© 2003-2006 Alan Green