Django 以编程方式创建组:Can';无法从迁移中访问权限

Django 以编程方式创建组:Can';无法从迁移中访问权限,django,permissions,migration,Django,Permissions,Migration,看到后,我尝试使用此迁移在项目设置中创建自己的组: from django.db import migrations from django.contrib.auth.models import Group, Permission def create_group(apps, schema_editor): group, created = Group.objects.get_or_create(name='thing_managers') if created:

看到后,我尝试使用此迁移在项目设置中创建自己的组:

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

def create_group(apps, schema_editor):
    group, created = Group.objects.get_or_create(name='thing_managers')
    if created:
        add_thing = Permission.objects.get(codename='add_thing')
        group.permissions.add(add_thing)
        group.save()

class Migration(migrations.Migration):

    dependencies = [
        ('main', '0002_auto_20160720_1809'),
    ]

    operations = [
        migrations.RunPython(create_group),
    ]
但我得到了以下错误:

django.contrib.auth.models.DoesNotExist: Permission matching query does not exist.
这是我的模型:

class Thing(models.Model):
    pass
为什么我不能那样做?我怎样才能解决这个问题


我使用django 1.9

权限是在
post\u migrate
信号中创建的。它们在添加新模型后第一次运行迁移时不存在。手动运行
post\u migrate
可能是最简单的方法:

from django.contrib.auth.management import create_permissions

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

    group, created = Group.objects.get_or_create(name='thing_managers')
    if created:
        add_thing = Permission.objects.get(codename='add_thing')
        group.permissions.add(add_thing)
        group.save()

create_permissions
检查现有权限,这样就不会创建任何重复的权限

一种解决方案是在尝试附加权限之前调用update\u permissions命令

from django.core.management import call_command

def update_permissions(schema, group):
    call_command('update_permissions')


operations = [
        migrations.RunPython(update_permissions, reverse_code=migrations.RunPython.noop),
        migrations.RunPython(create_group),
    ]
如前所述,请勿导入组和权限模型使用:

Group = apps.get_model("auth","Group")
Permission = apps.get_model("auth","Permission")
从中,以下是在Django 3.0.4中对我起作用的内容,显然将在>=1.9中起作用:

from django.core.management.sql import emit_post_migrate_signal

def create_group(apps, schema_editor):
    # Ensure permissions and content types have been created.
    db_alias = schema_editor.connection.alias
    emit_post_migrate_signal(2, False, db_alias)
    # Now the content types and permissions should exist

    Permission = apps.get_model('auth', 'Permission')
    ...

首先,您不应该从django.contrib.auth.models导入组、权限导入模型,而应该使用
apps.get\u model(“某些应用”、“模型名称”)
。第二个错误很明显-你没有
codename='add_thing'
的权限,但是在这种情况下,我链接的另一篇文章的答案应该如何工作?可能权限创建过程自1.7版以来发生了更改?我尝试了您的解决方案,但仍然有相同的错误。您尝试获取的权限是哪种型号的?模型是否在上一次迁移中在同一个应用程序中创建?否则,您可能必须访问定义了模型的应用程序。对于my
main
应用程序中的
Thing
模型。该模型是在models.py文件中创建的,在此之前我没有涉及迁移。