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 management.py, in your application directory (the same directory as models.py).


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

def init_data():
    # Your initialisation code here
    pass

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 management.py. 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)

Comments

At 13:47, 03 Aug 2006 David Avraamides wrote:

Nice. I've been handling this in a separate .py file (which I need to remember to run whenever I modify the models and resync). This is much cleaner and gets around the problems with the SQL initial data (when you need to do things in the Python world to create your data).

(#)
At 13:47, 03 Aug 2006 David Avraamides wrote:

Nice. I've been handling this in a separate .py file (which I need to remember to run whenever I modify the models and resync). This is much cleaner and gets around the problems with the SQL initial data (when you need to do things in the Python world to create your data).

(#)
At 09:36, 05 Sep 2006 David Blewett wrote:

I wasn't able to get this to work using the same dispatcher.connect line. I had to use this:

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

i.e., omit the sender= arg.

(#)
At 20:15, 22 Sep 2006 Eddy Mulyono wrote:

David Blewett wrote:
> i.e., omit the sender= arg.

Omitting the sender causes the signal to be sent twice for me. I have two INSTALLED_APPS: django.contrib.admin and my application.

Solution: edit "from myproj.myapp import models" to suit your project-application.

(#)

Add Comment




(Not displayed)






(Leave blank line between paragraphs. URLs converted to links. HTML stripped. Indented source code will be formatted with <pre> tags.)




© 2003-2006 Alan Green