首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在迁移中获取模型ContentType - Django 1.7

在迁移中获取模型ContentType - Django 1.7
EN

Stack Overflow用户
提问于 2014-10-20 11:41:09
回答 7查看 12.8K关注 0票数 49

我有一个更新某些权限的数据迁移。我知道迁移中存在一些已知的权限问题,通过在迁移中创建权限(而不是使用模型中的元组快捷方式),我可以避免一些麻烦。

迁徙:

代码语言:javascript
运行
复制
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings

def create_feature_groups(apps, schema_editor):
    app = models.get_app('myauth')

    Group = apps.get_model("auth", "Group")
    pro = Group.objects.create(name='pro')

    Permission = apps.get_model("auth", "Permission")
    ContentType = apps.get_model("contenttypes", "ContentType")
    invitation_contenttype = ContentType.objects.get(name='Invitation')

    send_invitation = Permission.objects.create(
         codename='send_invitation',
         name='Can send Invitation',
         content_type=invitation_contenttype)

    pro.permissions.add(receive_invitation)    

class Migration(migrations.Migration):

    dependencies = [
        ('myauth', '0002_initial_data'),
    ]

    operations = [
            migrations.RunPython(create_feature_groups),
    ]

经过一些尝试和错误之后,我能够使用manage.py migrate完成这项工作,但是我在测试manage.py test中得到了错误。

代码语言:javascript
运行
复制
__fake__.DoesNotExist: ContentType matching query does not exist.

调试时发现,在测试中运行时,迁移过程中此时没有ContentType (不确定原因)。按照这个帖子中的建议,我尝试在迁移它自己的过程中手动更新内容类型。加:

代码语言:javascript
运行
复制
from django.contrib.contenttypes.management import update_contenttypes
update_contenttypes(app, models.get_models())

在获取Invitation模型的内容类型之前。得到以下错误

代码语言:javascript
运行
复制
  File "C:\Python27\lib\site-packages\django-1.7-py2.7.egg\django\contrib\contenttypes\management.py", line 14, in update_contenttypes
    if not app_config.models_module:
AttributeError: 'module' object has no attribute 'models_module'

必须有某种方法来以可测试的方式在数据迁移中创建/更新权限。

谢谢。

编辑

最后通过添加

代码语言:javascript
运行
复制
from django.contrib.contenttypes.management import update_all_contenttypes
update_all_contenttypes() 

奇怪的是,这个是不够的。

代码语言:javascript
运行
复制
update_contenttypes(apps.app_configs['contenttypes'])

我很想知道为什么这一切都是必要的

EN

Stack Overflow用户

发布于 2019-09-30 14:17:33

对于Django 2.1,我必须从全局注册表导入应用程序,因为传入迁移的应用程序是django.db.migrations.state.AppConfigStub的实例,没有填充的models_module属性。create_contenttypes正在检查这个属性。

代码语言:javascript
运行
复制
from django.apps.registry import Apps, apps as global_apps
from django.contrib.contenttypes.management import create_contenttypes
from django.db import migrations


def add_permision(apps: Apps, schema_editor):
    my_app_config = global_apps.get_app_config('my_app')
    create_contenttypes(my_app_config)

    ...
票数 16
EN
查看全部 7 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26464838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档