Insert Initial Data via Django ORM
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.
Works great, nice job.
Ditto, good solution. Thanks.
very interesting, but I don’t agree with you
Idetrorce
Freakin’ sweet! Works like a charm.
The trunk has had the ability to use fixtures for a while now, which will provide similar functionality.
@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.
This was immensely useful in figuring out how to hook up inserting PostGIS SQL for unit tests in a GeoDjango app. Thanks!
Thanks for this post. I am new at python and this was a big help.
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)
Thank u