我有一个更新一些权限的数据迁移。我知道迁移中的权限存在一些已知问题,并且我能够通过在迁移中创建权限来避免一些麻烦(而不是使用模型中的元组快捷方式)。
迁移:
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
在测试中运行时,此时迁移中没有(不知道为什么)。按照这篇文章中的建议,我尝试在它自己的迁移中手动更新内容类型。添加 :
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'])
我很想知道为什么所有这些都是必要的