Django fixtures for permissions

懵懂的女人 提交于 2019-11-30 18:50:29
Filip Dupanović

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.

jonpa

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!