'django permissions: new permission is inserted after all other migrations

I added a new permission to my model, and than used manage.py makemigrations. it created a migration that alters the model options (specificly the permisions..).

later , I added a migration that has a dependency on that first migration, and uses the permission (that i believed the first migration created). that migration used the permission in a RunSQL operation that queried auth_permissions.

as i debugged the migrations - i realized that the insert to the auth permission only happens after all of the migrations have been applied.

meaning - when i try to query the id of the permission in order to use it in the second migration - it doesn't exist and so the second migration doesn't behave as expected.

any idea why this happens and how to prevent it? my assumption when adding a new permission was that it will be added with the migration that django created for me..and not at a different stage.

Thanks!



Solution 1:[1]

This is an old but still valid topic. The answer is that Django only marks permissions for creation. They actually get created in the post_migrate signal, which is only fired once migrations successfully ran through. Meaning if migration X creates a permission and migration Y uses it, you need to migrate in two steps. Stop after X and before Y, then migrate the rest. This is the official way, but not always applicable (for example, automatic testing generates new databases and doesnt exactly like this procedure).

You can work around this by creating a fake permission in the migration that needs it. This works since permissions are only created once. However, you will have to repeat this for any migration that needs these permissions, and you need to make sure they match the actual permissions defined (for example, they should have a name if you need one). Example can be found here: https://stackoverflow.com/a/31543063

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fabian