Loading initial data for your Django app using fixtures and South
I’ve been thinking about deployment for my app these last few days and one of the things I needed to be able to do is automatically load initial data to one of the tables. If you’re already using South (which you should be unless you have a very, very simple project), you can easily include this in a data migration by loading in a fixture.
You can accomplish this in a few simple steps:
1. Export the data from the table to a JSON file, you can use a Django dumpdata command to do this. For example:
python manage.py dumpdata glucoses.category –settings=settings.local > fixtures/initial_glucoses_category_data.json
2. Create a migration. For example:
python manage.py datamigration glucoses load_categoryfixture –settings=settings.local
3. Edit the migration file so the forwards method looks something like this:
class Migration(DataMigration): def forwards(self, orm): from django.core.management import call_command call_command("loaddata", "fixtures/initial_glucoses_category_data.json")
That’s it, you’re done! Now when you deploy your app to a new environment with a new database and run the South migration, the table will be populated with your fixture automatically at the correct time.
More information here: http://south.readthedocs.org/en/latest/fixtures.html