我正在从 django 1.8 迁移到 django 1.9。
我有一个迁移,它添加了一个组user
,然后向该组添加了django_comments.add_comment
权限。适用于 django 1.8 的迁移如下所示
from django.contrib.contenttypes.management import update_contenttypes from django.contrib.auth.management import create_permissions def create_perms(apps, schema_editor): update_contenttypes(apps.get_app_config('django_comments')) create_permissions(apps.get_app_config('django_comments')) Group = apps.get_model('auth', 'Group') group = Group(name='user') group.save() commentct = ContentType.objects.get_for_model(apps.get_model('django_comments', 'comment')) group.permissions.add([Permission.objects.get(codename='add_comment', content_type_id=commentct)]) group.save() class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('django_comments', '0002_update_user_email_field_length') ] operations = [ migrations.RunPython(create_perms, remove_perms) ]
升级到 django 1.9 时,会抛出错误,因为找不到 contenttype。这是因为 update_contenttypes
调用时未创建必要的 content_types。该函数中有这一行( django's source code reference )
def update_contenttypes(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs): if not app_config.models_module: return ...
这个app_config.models_module
在django 1.9中是None
,但在django 1.8中是不是None
如果我将其替换为此代码
def update_contenttypes(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs): if not app_config.models_module: #return pass ...
然后一切正常。
问题是我不想改变 django 的核心代码。如何在 django 1.9 中实现此功能?
最佳答案
好的,感谢#django IRC(用户 knbk)中的一些帮助,我找到了一个丑陋的解决方法,但至少它有效!
更改这两行
update_contenttypes(apps.get_app_config('django_comments')) create_permissions(apps.get_app_config('django_comments'))
写这个来代替
app = apps.get_app_config('django_comments') app.models_module = app.models_module or True update_contenttypes(app) create_permissions(app)
现在一切正常了。
关于迁移应用程序中缺少 django 1.9 models_module,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35350752/