Adding groups via Django DB migration script and assigning a group to all existing users

In one of my projects, we realized that we wanted to use Django Groups. We had some users in DB without any group. I wanted to create new groups and add existing users to one group.

I’ve decided to use migration for this.

First, I created an empty migration script.

python manage.py makemigrations users --empty

Next, I modified the created file to add proper migration.

from django.db import migrations
def apply_migration(apps, schema_editor):
db_alias = schema_editor.connection.alias
Group = apps.get_model("auth", "Group")
Group.objects.using(db_alias).bulk_create(
[Group(name="group1"), Group(name="group2")]
)
driver_group = Group.objects.using(db_alias).get(name="group1")
User = apps.get_model("users", "User")
users = User.objects.using(db_alias)
driver_group.user_set.add(*users)
def revert_migration(apps, schema_editor):
Group = apps.get_model("auth", "Group")
Group.objects.filter(name__in=["group1", "group2"]).delete()
class Migration(migrations.Migration):
dependencies = [("users", "0005_auto_20190724_0727")]
operations = [migrations.RunPython(apply_migration, revert_migration)]