【发布时间】:2014-11-25 22:46:15
【问题描述】:
我正在尝试使用 django 1.7 本机迁移系统实现数据迁移。这是我所做的。
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_basic_user_group(apps, schema_editor):
"""Forward data migration that create the basic_user group
"""
Group = apps.get_model('auth', 'Group')
Permission = apps.get_model('auth', 'Permission')
group = Group(name='basic_user')
group.save()
perm_codenames = (
'add_stuff',
'...',
)
# we prefere looping over all these in order to be sure to fetch them all
perms = [Permission.objects.get(codename=codename)
for codename in perm_codenames]
group.permissions.add(*perms)
group.save()
def remove_basic_user_group(apps, schema_editor):
"""Backward data migration that remove the basic_user group
"""
group = Group.objects.get(name='basic_user')
group.delete()
class Migration(migrations.Migration):
"""This migrations automatically create the basic_user group.
"""
dependencies = [
]
operations = [
migrations.RunPython(create_basic_user_group, remove_basic_user_group),
]
但是当我尝试运行迁移时,我收到了一个 LookupError 异常,告诉我找不到标签为“auth”的应用程序。
我怎样才能以简洁的方式创建我的组,也可以在单元测试中使用?
【问题讨论】:
-
尝试
app.get_registered_model和/或依赖('auth', 'group')。这是一种随机的建议,因为我自己仍在了解注册表的过程中。它帮助我解决了一个类似的问题。 -
在 django 1.8 中,对象管理器可以在迁移期间使用。特别是现在您的代码应该按原样工作