[Fixed]-Right way to create a django data migration that creates a group?

28👍

This is how I do it:

from django.db import models, migrations


def apply_migration(apps, schema_editor):
    Group = apps.get_model('auth', 'Group')
    Group.objects.bulk_create([
        Group(name=u'group1'),
        Group(name=u'group2'),
        Group(name=u'group3'),
    ])


def revert_migration(apps, schema_editor):
    Group = apps.get_model('auth', 'Group')
    Group.objects.filter(
        name__in=[
            u'group1',
            u'group2',
            u'group3',
        ]
    ).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('someapp', 'XXXX_some_migration'),
    ]

    operations = [
        migrations.RunPython(apply_migration, revert_migration)
    ]

Although, there must be a more Djangonic way.

👤César

7👍

Answer from César is correct. To make it more Django create the migration file automatically by going to your django app root folder and entering:

python manage.py makemigrations <yourappname> --empty

Note: You may need python3 instead of python depending on your system configuration.

This creates an empty migration file in a sub directory of your app called 0001_initial.py

You can then alter it as per César instructions. Which worked correctly with Django 2.2

Leave a comment