Exporting user related data to json fixture with django-fixture-magic

When looking for painless fixture creation based on user data for test purpose I found django-fixture-magic package quite useful and meeting my expectations.

Installing django-fixture-magic:

pip install django-fixture-magic

Then updating settings.py:

INSTALLED_APPS = (
    ...
    'fixture_magic',
    ...
)

From four available commands two are especially interesting:

  • dump_object which returns json representation of a specific object as well as all its dependencies defined by FK.
  • merge_fixtures which eliminate duplicates and merge fixtures

Example of dumping user data:

 
./manage.py dump_object APP.MODEL1 --query '{"user__id": USER_ID}' > user_data.json 

dump_object follows FK so all related objects will be included in the fixture.

It works perfectly with many-to-one relationships. Some workaround can be done in case that user related data is represented by more unrelated models or extra one-two-one or many-to-many ralationships are used.

Steps are:

  • creating separate partial fixtures with dump_object
  • combining them together into complete one with merge_fixtures

Example:

#!/bin/bash

# Some validation
if [[ $# -eq 0 ]] ; then
    echo 'Usage '$0' USER_ID'
    exit 0
fi
 
./manage.py dump_object APP1.SOME_MODEL --query '{"user__id": '$1'}' > user_$1_part1.json
./manage.py dump_object APP2.OTHER_MODEL --query '{"user__id": '$1'}' > user_$1_part2.json
./manage.py merge_fixtures user_$1_part1.json user_$1_part2.json > user_$1_data.json
rm user_$1_part*.json