Introducing Django Pyfixtures

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.

import datetime
import pytz
from models import Organization
from models import Group
from models import Contact

organization1 = Organization(
    create_date=datetime.datetime(2011, 1, 15, 44, 0, tzinfo=pytz.timezone('UTC')),
    name=u'Marvel Comics')

group1 = Group(
    create_date=datetime.datetime(2011, 5, 17, 1, 59, 14, tzinfo=pytz.timezone('UTC')),
    name=u'The Avengers',

contact1 = Contact(
    name=u'Captain America',
    create_date=datetime.datetime(2010, 6, 17, 1, 48, 32, tzinfo=pytz.timezone('UTC')))

contact2 = Contact(
    name=u'Iron Man',
    create_date=datetime.datetime(2010, 6, 17, 1, 48, 32, tzinfo=pytz.timezone('UTC')))

Getting Started

  • pip install django-pyfixtures
  • Edit
SERIALIZATION_MODULES = {'py': 'pyfixtures.serializer'}
  • Convert your existing fixtures to python, and test them
./ loaddata fixtures/initial_data.json
./ dumpdata --exclude contenttypes --format=py > fixtures/
./ loaddata fixtures/

I'm currently working at NerdWallet, a startup in San Francisco trying to bring clarity to all of life's financial decisions. We're hiring like crazy. Hit me up on Twitter, I would love to talk.

Follow @chase_seibert on Twitter