Django.fun

Django manual migration to add group

I am attempting to create a migration that will automatically add a group and permissions to the group when it is run. I adapted some code from the docs and an example. I can get the migration to add the group but not the permissions. I am getting the following error: TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use permissions.set() instead. I am not sure how to implement this suggestion. Any ideas?

The migration:


from django.db import migrations, models
from django.contrib.auth.models import Group, Permission
from django.contrib.auth.management import create_permissions



def add_group_permissions(apps, schema_editor):
    for app_config in apps.get_app_configs():
        create_permissions(app_config, apps=apps, verbosity=0)

    # Employee
    group, created = Group.objects.get_or_create(name='Employee')
    if created:
        permissions_qs = Permission.objects.filter(
                         codename__in=[
                                         'can_add_how_to_entry',
                                         'can_change_how_to_entry',
                                         'can_view_how_to_entry',
                                                      ]
        )
        group.permissions = permissions_qs
        group.save()

class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(add_group_permissions),
    ]

Remember that group.permissions is a related query manager, not a field, so if you assign something to that you will destroy it. So you need to do something like:

permissions_qs = Permission.objects ...
for permission in permissions_qs:
    group.permissions.add(permission)
group.save()