Henrik speaking at a conference

Hi, I’m Henrik Joreteg

Mobile web consultant, developer, and speaker

posts | twitter | email | hire | book | my startup: Xchart.com

Using Fixtures and SQLite for easy dev in Django

When I’m building out a new app I don’t want to deal with setting up databases or repeatedly entering dummy data if I make changes to my models. Django fixtures and SQLite to the rescue!

Here’s how I do it:

In my settings.py here are my relevant db settings:

# create site root variable
import os 
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))

DATABASE_NAME = os.path.join(SITE_ROOT, 'dev.db')

Now, when I define my models.py and then run python manage.py syncdb, Django will create all the tables for me based on my models and put the entire database in a single self-contained file called dev.db at the root of my project folder.

Then I can enter my test data in the amazing auto-generated django admin.

Now, to create my fixtures, all I have to do it run:

python manage.py dumpdata --indent=4 > my_app_name/fixtures/initial_data.json

(If your django app doesn’t already have a “fixtures” directory, you’ll have to create it first.)

This command will write all your data to a JSON file. The --indent=4 flag is just so it’s easier to read. But after running this command look in your fixtures folder you’ll see a initial_data.json file that looks something like this:

    "model": "myapp.person",
    "pk": 1,
    "fields": {
      "first_name": "John",
      "last_name": "Lennon"
    "model": "myapp.person",
    "pk": 2,
    "fields": {
      "first_name": "Paul",
      "last_name": "McCartney"

But here’s the kicker… now, if for some reason you need to delete your entire dev.db database, all you have to do is run python manage.py syncdb, and it will automatically re-inflate the database with all your test data! Pretty freakin’ sweet eh? (no I’m not canadian).

Obviously, if you make changes to your models that the dummy data incorrect, this trick won’t help you much. But it’s perfect for the models that probably won’t change so much during development.

So, thanks to Django you can now quickly whip up a prototype without having to build a database or worry about database drivers, AND you can even completely delete your database without losing all your test/dummy data. So sweet!

This one deserves the #awesomecode tag IMHO.