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.