Django Fixures

Amit S Kulkarni
2 min readJul 29, 2021

Thought of writing this blog as I had lot of issues to make fixtures work in django. There are various steps to get the fixtures working in django. First is to get the database dump, create the fixture testdata from that dump by using dumpdata command and then loading that by using loaddata and finally declaring the fixtures in the test to use it.

Steps involved in creating the fixture

1. Get the Database dump and restore it using Postgres GUI or below command:

pg_restore -U postgres -d ‘databasename’ -1 ‘dumpfilename’

2. Set the databasename used above as default in your django project settings.py

3. Create a fixtures directory under the django project app directory (for e.g. appname/fixtures)

4. Run the dumpdata command from app directory:

python -Xutf8 .\manage.py dumpdata ‘app_label.model’ — settings=’settings file’ > appdirectory\fixtures\testData.json

-Xutf8 option is used to resolve the codec errors

app_label.model for e.g. appname.modelname

5. The dumped json file needs to be processed for loaddata to work. Remove some json fields which are not required.

for e.g. “tags” or “createdate” field can be removed if getting error while executing loaddata. Also, don’t need all of the dumped json file. There can be 1000 records. so just take whatever is required for testing (for e.g. 5–10 records).

6. Run loaddata with that processed json file (testData.json) from app directory

python manage.py loaddata appdirectory\fixtures\testData.json — settings=’settings file’

if success it will show “Installed 10 object(s) from 1 fixture(s)”

7. The fixtures json file is now ready to be used for testing and can be checked for the model contents

8. Declare the fixtures before executing the tests in your test file

fixtures = [‘testData.json’]

This is the key where to declare the fixtures and is not clearly mentioned in django project docs. It should be declared under the class and not inside the setUp def functions, otherwise django can’t find it.

The big thing that the Django Testcase does for you in regards to fixtures is that it maintains a consistent state for all of your tests. Before each test is run, the database is flushed: returning it to a pristine state (like after your first syncdb). Then your fixture gets loaded into the DB, then setUp() is called, then your test is run, then tearDown() is called.

--

--

Amit S Kulkarni
Amit S Kulkarni

Written by Amit S Kulkarni

Software Engineer. Application Security | Penetration | Automation Evangelist. Python |Javascript. OWASP Chapter Lead (Perth) @amtoya on Twitter

Responses (1)