Search code examples
pythondjangodjango-ormdjango-authenticationdjango-migrations

Django: managing permissions, groups and users during data migrations


Problem

During a data migration, I'm trying to create a django.contrib.auth.models.Group and some Users and then attaching said group to one of the users.

Problem I'm finding (other than the permissions still not being created, but I've already found a solution to that), is that for some reason the many-to-many manager doesn't seem to be working as it should (?).

Basically what I'm trying to do is something like:

group = Group.objects.create(name="manager")
# user creation...
user.groups.add(group)

However, I get the following error:

TypeError: Group instance expected, got <Group: manager>

Whenever I try to replicate this in the Django shell, it works without any problem. It only fails while doing migration. Any ideas?

Things I've tried and other information

  • I've tried both populating the m2m relation through the User related manager and the Group related manager, that is, user.groups.add(group) and group.user_set.add(user). Both give me a similar error.
  • Just partially related, but just so I have the permissions needed, I have this first in my migration:
for app_config in apps.get_app_configs():
    app_config.models_module = True
    create_permissions(app_config, verbosity=0)
    app_config.models_module = None
  • The group is supposedly created properly. Given that I create the groups and the users in different helper functions, I actually grab the group with Group.objects.get(name="manager"), and when printing, it shows the correct information.

Solution

  • Turns out that the problem comes up when you use the django.contrib.auth.models.Group model directly. If instead you use apps.get_model("auth.Group"), everything works fine.