Categorized: Database, Django

Use Django Fixtures to Automatically Load Data when You Install an App

First, load some data via the admin that should always be there when someone installs the app.

Next, dump that data out into JSON format into a fixture:

./manage.py dumpdata [app_name] > [app_name]/fixtures/initial_data.json

Now whenever someone installs the app and runs syncdb, they’ll get that initial data loaded into their database.

Sources

Comments

Trey → October 21st, 2008 at 3:11 pm

Something about this setup makes me think it could be used to do some basic data migration.

  • Load data in the database.
  • Change schema in models.py.
  • Run a magical script that
    • Creates a fixture from the existing data
    • Wipes the database
    • Syncs the database from the schema
    • Reloads data from the fixtures

It’s not versioned like a proper migration, but it would be better than the default option of creating new fields manually.

Josh Kersey → April 27th, 2009 at 2:21 pm

I second the motion for the magical script. Especially one that would reload data from all available fixtures or at least give the ability to specify more than one fixture. Good call.

Josh Kersey → April 27th, 2009 at 2:22 pm
  • Test of Trey’s WMD

    • in his solutions log.

    This is a pretty cool trick.

What…another paragraph.

Tanner Netterville → April 27th, 2009 at 2:52 pm

Haven’t looked into this too deeply but my common process for updating a model is basically the same thing:

  1. Make changes to the model, but don’t save
  2. $ python manage.py dumpdata [app] > dump.json
  3. Save the changed models.py
  4. $ python manage.py reset [app]
  5. $ python manage.py loaddata dump.json

I thought about trying to automate this because it happens fairly regularly with new apps, but I haven’t devoted time to it because in order to use dumpdata the model has to match the database or it will throw errors.

When I get ahead of myself and save before I dumpdata I have to go back and comment out the new field or revert the changed field temporarily.

I think this definitely warrants some good time and effort.

Tanner Netterville → April 27th, 2009 at 2:54 pm

one more thing about my method, my file dump.json… at any given moment I have no idea what is in it, I always overwrite the same file as I am about to reset and load it.

What do you think about that?

Elsewhere in the empire: Home, Blog, APOD