【发布时间】:2014-12-15 09:18:02
【问题描述】:
我有一个更新一些权限的数据迁移。我知道迁移中的权限存在一些已知问题,并且我能够通过在迁移中自行创建权限来避免一些麻烦(而不是使用模型中的元组快捷方式)。
迁移:
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 中遇到错误。
__fake__.DoesNotExist: ContentType matching query does not exist.
调试了一下发现在测试中运行时迁移此时没有ContentType(不知道为什么)。按照post 中的建议,我尝试在它自己的迁移中手动更新内容类型。补充:
from django.contrib.contenttypes.management import update_contenttypes
update_contenttypes(app, models.get_models())
在获取 Invitation 模型的内容类型之前。出现以下错误
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'
必须有某种方法以可测试的方式在数据迁移中创建/更新权限。
谢谢。
编辑
终于通过添加让它工作了
from django.contrib.contenttypes.management import update_all_contenttypes
update_all_contenttypes()
奇怪的是,这个还不够
update_contenttypes(apps.app_configs['contenttypes'])
我很想知道为什么所有这些都是必要的
【问题讨论】:
-
对于 Django 1.8 上想要 update_all_contenttypes 的人,请参考这个问题:stackoverflow.com/questions/29550102/…
-
我发誓,在与 Django 合作的 3 年中,我从来没有像处理这个问题那样讨厌它(好吧,我在撒谎,还有其他粗糙的补丁在我们过去的关系中也是如此)。无论如何,这些 Q/A 被标记为圣杯,非常感谢!
-
保持坚强塞巴斯蒂安????
标签: django django-1.7 django-migrations