Django fixtures were initially touted as a great way to pre-populate your database, mainly for testing. Over time, various community leaders have suggested that fixtures are slow, brittle, should be bundled instead of loaded from scratch for every unit test and should probably be replaced with class factories.
If you’re starting from scratch, that’s great advice. But how do you get there if you already have a bunch of fixtures? Starting today, you can use django-pyfixtures to convert your json fixtures to python code.
Using the regular Django dumpdata command, pyfixtures will generate a python file that contains all the code necessary to re-constitute that data in an empty database. You can take that code and refactor it into something you maintain going forward, or you can re-generate it from a target database when needed.
How it works
Pyfixtures implements a new Django serializer that takes a model object stream and produces python constructors for that code. It ends up looking just as it would if you wrote the code by hand, complete with necessary imports, declaring models that other models depend on first, and using previously declared variables for foreign keys. It can also deal with circular references by letting the user decide which models to use primary keys for, instead of references.
Here is an example of what a fixture might look like.
pip install django-pyfixtures
- Convert your existing fixtures to python, and test them