15

I would like to create data migrations that create Permissions and Groups, so that my other developers can just run the migrations and get everything set up. I was able to create the migrations and run them just fine, but now I'm getting an error when running my tests.

But if I do this:

from django.contrib.auth.models import Group

def add_operations_group(apps, schema_editor):
    Group.objects.get_or_create(name='operations')

I get:

django.db.utils.OperationalError: no such table: auth_group

If I do this:

def add_operations_group(apps, schema_editor):
    Group = apps.get_model("django.contrib.auth", "group")
    Group.objects.get_or_create(name='operations')

I get:

LookupError: No installed app with label 'django.contrib.auth'

Is there a way to do this? Or is there a "Django Way" to make sure things like permissions and groups are created?

Chris Curvey
  • 9,738
  • 10
  • 48
  • 70

2 Answers2

27

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
  • 9,939
  • 6
  • 53
  • 74
  • 1
    Drat. I tried it your way, and I'm still getting "no installed app with label 'auth'" – Chris Curvey Nov 03 '15 at 14:39
  • 1
    ` from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('someapp', 'XXXX_some_migration'), ]` Add reference to django auth model in dependency – mithuntnt Mar 11 '17 at 06:11
  • nice, thanks! But why do we need to revert migration? – Ladenkov Vladislav May 31 '20 at 11:16
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

Jonathan Homer
  • 136
  • 1
  • 3