Create groups and add permissions to them in migrations

Hi all,

I’d like to automatically create groups and add custom permissions and some normal permission to them.

After a lot of googling I found a solution that seems ok to me, but I don’t know if it is a good practice.
I post the link of the page, If I can’t do that, let me know and I’ll remove it:

link

First question:
In that code when the migration runs, all permissions are created before django tries to do that. Is it ok?

Second question:
If I like (for example in two months) to add a new group and assign some permission to it, I have to create a new migration and when the migration runs, all permissions are created again (it will be tried to create all the permissions again). Is it ok?

Thanks in Advance,

supermario18b

the code that I’m worried about, that will be executed every time (every migration), is:

# Permissions have to be created before applying them
for app_config in apps.get_app_configs():
	app_config.models_module = True
	create_permissions(app_config, verbosity=0)
	app_config.models_module = None

I checked the code of the “create_permission” function and it will only be tried to add a permission if not present.

perms = [
        Permission(codename=codename, name=name, content_type=ct)
        for ct, (codename, name) in searched_perms
        if (ct.pk, codename) not in all_perms
    ]
    Permission.objects.using(using).bulk_create(perms)

I tested and it seems to work just fine. If someone else needs to automatically add groups and assign permission to them, this could be a way :slight_smile: