Home Blog CV Projects Patterns Notes Book Colophon Search

Django Fixture Format

Django has a tool for backing up models as JSON. You can dump everything like this:

python3 manage.py dumpdata --indent=2 > dump.json

With this invocation, each model will have a pk entry which corresponds to the ID of the object.

If you design your models carefully you can use natural foreign and primary keys. This means that no pk will be added to the model, and when models have foreign keys to others you can use natural keys.

Here's how to use it:

python3 manage.py dumpdata --natural-foreign --natural-primary webpage pages --indent=2 > dump.json

This time foreign keys are are referenced by their natural key. For example:

    "webpage": [
      "old-home"
    ],
    "asset": [
      "old-home",
      "old-home/_asset/vid.mp4"
    ],

The advantage of this is that your dump won't depend on the specific IDs that happened to be chosen by the database when the models were created.

This means you can restore multiple dumps, or restore certain models over the top of other models which gives you a bit more flexibility.

There's one niggle though. If you use inherited models together with --natural-foregin and --natural-primary they don't work correctly with Django < 2.2 when you restore them with loaddata. Luckily there is also a --format=patched_json argument which allows you to specify your own technique for dumping data.

See https://code.djangoproject.com/ticket/24607 and https://github.com/django/django/pull/8370 and https://gist.github.com/cybojenix/2476434c513170d2f267cb588a8d645b for some links to solutions.

Copyright James Gardner 1996-2020 All Rights Reserved. Admin.