Loading or modifying fixtures with Django 1.7 and onwards

With Django 1.2 (the older version that I was using before), uploading new data in a fixture table was as easy as modifying the JSON fixture file and running manage.py syncdb. But it doesn’t work anymore and will be deprecated in Django 1.9. Django came up with a little complicated process which made me feel nervous. But after running it once on my development machine, it works wonders for me. I got ideas from the following 2 posts:

Django Documentation
Stack Overflow

Here’s what I followed for my own notes:
1. Create an empty migration file

python manage.py makemigrations --empty app_name

This would create an empty migration file that I modified to load the new fixture data

2. Modify the JSON content in the fixture file

3. Modify the file created in Step 1 by setting the appropriate migration code

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
from django.core import serializers
import os

fixture_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../fixtures'))
fixture_filename = 'initial_data.json'

def load_fixture(apps, schema_editor):
    fixture_file = os.path.join(fixture_dir, fixture_filename)

    fixture = open(fixture_file, 'rb')
    objects = serializers.deserialize('json', fixture, ignorenonexistent=True)
    for obj in objects:

class Migration(migrations.Migration):

    dependencies = [
        ('app_name', '000X_last_migration_file_number'),

    operations = [

The load_fixture is a custom function defined in the empty migration file that was created and called in the migrations.RunPython command that takes a callable parameter.

4. Finally, run migrate to load the fixture into the database

python manage.py migrate

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s