我有一個數據遷移更新了一些權限。我知道有一些已知的遷移權限問題,我可以通過在遷移中創建權限(而不是使用模型中的元組快捷方式)來避免一些麻煩。在遷移中獲取模型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