How to Export and Import Fixtures in Django

neotam Avatar

How to Export and Import Fixtures in Django
Posted on :

Tags :

A fixture is a collection of file that hold the serialized content of the database. Files that comprise the fixture can be distributed across multiple directories and application in the Django project

Fixtures are useful to prepopulate selected tables with specific data or to load dummy data for tests

Typical locations that Django would search for fixtures are

  • “fixtures” directory of every installed app
  • All directories named in FIXTURE_DIRS setting (in
  • Or, literal path passed as command line argument to command

The Django admin command “dumpdata” can be used to create fixtures those can also be used as input for loaddata to load data to database

Use dumpdata command to create fixtures from existing data in database. Syntax of dumpdata is as follows

django-admin dumpdata [app_label[.ModelName] [app_label[.ModelName] …]]

Other command line options available

-all, -aDump all
–format FORMATSpecify the valid FORMAT in which data must be dumped
–indent INDENT
–exclude EXCLUDE, -e EXCLUDE
–database DATABASE
–output OUTPUT, -o OUTPUTFile to write the serialized data

For example I would like to dump TicketStatus from django app “api”

python dumpdata api.TicketStatus

By default serialized data is written to standard output, to direct it to file use command line argument –output

python dumpdata api.TicketStatus --output api/fixtures/ticket_status.json

Make sure given recursive directories of given path exist

Load data into database using fixutres using command “loaddata”. Syntax of the command “loadata” is as follows

usage: loaddata [-h] [--database DATABASE] [--app APP_LABEL] [--ignorenonexistent] [-e EXCLUDE] [--format FORMAT] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color]
                           [--force-color] [--skip-checks]
                           fixture [fixture …]

For example

python loaddata status 

Where status is the fixture json file. We do not need to provide extension when loading initial data through command loaddata. Also no need to provide location if fixtures are located in the app director inside fixtures folder. loaddata command checks for the fixtures according to the precedence

Leave a Reply

Your email address will not be published. Required fields are marked *