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.