Skip to content

Latest commit

 

History

History
31 lines (19 loc) · 1.29 KB

2024-07-31-emit-post-migrate-signal.md

File metadata and controls

31 lines (19 loc) · 1.29 KB
tags
django

Force the creation of Permission objects associated with models during migration

Django models come with default permissions associated with them. Whenever a new Model is created in the database, there are also 4 default permissions that are created in the auth_permission table:

  • add_${modelName}

  • change_${modelName}

  • delete_${modelName}

  • view_${modelName}

These entries in the auth_permission table are created after the migrations are executed, when the post_migrate signal is emmited. Sometimes we need to create data migrations that creates certain Groups, and attaches permissions to them. But when no permission objects have been created, we can't select and attach them to groups during the migraion.

This is where one method in Django comes in handy, emit_post_migrate_signal.

from django.core.management.sql import emit_post_migrate_signal

def forward_migrate(apps, schema_editor):
    emit_post_migrate_signal(verbosity=2, interactive=False, db="default")
    # now you can select the Permissions from the DB

I actually had to google how to do it quite a few times, so I decided to make a TIL out of it, so I can find it faster next time.