So I’ve always wanted to know how to write the XML fixtures for automatically loading my project db with initial data, but I always thought I’d have to learn something so I stayed away and simply entered test data by hand.
Boy was I wrong.
I had to manually write shipping tables for several shipping categories / states and state tax rates so I wanted them in a fixture I could simply load into django anywhere else.
Turns out it is amazingly easy.
Note: I previously used format=xml in this example but I’ve since switched to json (the default) because I was getting parser errors when I tried to loaddata the xml files
python manage.py dumpdata --indent=4 > shipping_fixture.json
python manage.py dumpdata
dumps all of your apps. add your app afterwards to dump only one piece.
Notice the command simply has a long output and no options to save it to a file somewhere. That’s where you use > to specify a file to write the data to.
–indent=4 just adds indentation because the default writes all data at the beginning of the line.
python manage.py loaddata shipping_fixture.json will load your data. You can also add a default fixtures setting in settings.py to have commands like manage.py flush delete the db & repopulate with your fixture.
Great stuff.. who knew it would be so freaking easy.
2 responses so far ↓
Diarmuid Bourke // September 24, 2008 at 5:38 pm |
I spent 3 hours figuring out why my fixtures wouldn’t work thanks to the use of “>>” in this article.
Use “>” instead. It doesn’t append.
Yuji // September 24, 2008 at 6:18 pm |
Updated. >> is indeed append to file..
Sorry about your three hours!