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 settings.py)
- 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, -a | Dump all |
–format FORMAT | Specify the valid FORMAT in which data must be dumped |
–indent INDENT | |
–exclude EXCLUDE, -e EXCLUDE | |
–database DATABASE | |
–output OUTPUT, -o OUTPUT | File to write the serialized data |
For example I would like to dump TicketStatus from django app “api”
python manage.py dumpdata api.TicketStatus
By default serialized data is written to standard output, to direct it to file use command line argument –output
python manage.py 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: manage.py 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 manage.py 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