Django fixtures for permissions Django fixtures for permissions django django

Django fixtures for permissions


As of at least Django >=1.7, it is now possible to store permissions in fixtures due to the introduction of "natural keys" as a serialization option.

You can read more about natural keys in the Django serialization documentation

The documentation explicitly mentions the use case for natural keys being when..

...objects are automatically created by Django during the database synchronization process, the primary key of a given relationship isn’t easy to predict; it will depend on how and when migrate was executed. This is true for all models which automatically generate objects, notably including Permission, Group, and User.

So for your specific question, regarding auth_group_permissions, you would dump your fixture using the following syntax:

python manage.py dumpdata auth --natural-foreign --natural-primary -e auth.Permission

The auth_permissions table must be explicitly excluded with the -e flag as that table is populated by the migrate command and will already have data prior to loading fixtures.

This fixture would then be loaded in the same way as any other fixtures


The proper solution is to create the permissions in the same manner the framework itself does.

You should connect to the built-in post_migrate signal either in the module management.py or management/__init__.py and create the permissions there. The documentation does say that any work performed in response to the post_migrate signal should not perform any database schema alterations, but you should also note that the framework itself creates the permissions in response to this signal.

So I'd suggest that you take a look at the management module of the django.contrib.auth application to see how it's supposed to be done.


Just to add to @jonpa's comment, if you are using multitenant app and you want to directly save the fixtures to a file you can do:

python manage.py tenant_command dumpdata --schema=<schema_name> --natural-foreign --natural-primary -e auth.Permission --indent 4 > /path/to/fixtures/fixtures.json