(guest@joequery.me)~ $ |

Django test loaddata fixture not working [SOLVED]

If you're wanting to load fixtures in your Django unittests, you've probably tried the following:

  1. Using the fixtures class attribute of the TestCase
  2. Using the call_command helper to call the loaddata command

I'm going to assume if you've reached this article, you've already tried #1. In my personal case, the reason why #1 is probably failing is because I have altered the default Django project structure.

loaddata command not working

I ran into a strange issue where running call_command in a test seemed to load the fixtures correctly, but queries using the Models related to the fixtures were all returning empty.

Even though I would see X objects loaded from (Y) fixtures, the behavior was as if the fixtures hadn't been loaded at all.

The solution

Adding a commit=False option to the call_command invocation is all that was required to make loading fixtures work.

from django.core.management import call_command
call_command(
    'loaddata',
    'apps/search/fixtures/data.json',
    commit=False,
    verbosity=0
)

The explanation

After digging through the loaddata source (located at django/core/management/commands/loaddata.py), I found the following comment:

# commit is a stealth option - it isn't really useful as
# a command line option, but it can be useful when invoking
# loaddata from within another script.
# If commit=True, loaddata will use its own transaction;
# if commit=False, the data load SQL will become part of
# the transaction in place when loaddata was invoked.
commit = options.get('commit', True)

That's exactly what I needed!

Tagged as django

Date published - July 18, 2015