我有一个数据迁移更新了一些权限。我知道有一些已知的迁移权限问题,我可以通过在迁移中创建权限(而不是使用模型中的元组快捷方式)来避免一些麻烦。在迁移中获取模型ContentType - Django 1.7
迁移:
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,请参考这个问题:http://stackoverflow.com/questions/29550102/importerror-cannot -import-name-update-all-contenttypes – jstaab 2015-09-09 23:31:01